通过抓取 ElementRef 禁用按钮:angular2
Disabling a button by grabbing ElementRef: angular2
我正在尝试在单击按钮时将其禁用。通过单击我正在调用一个函数,我想禁用使用该函数的按钮。如何使用 ElementRef 访问按钮的 属性 并禁用它?我不是很熟悉如何使用 ElementRef。
任何帮助将不胜感激!
如果您真的想通过 ElementRef 禁用按钮,您可以使用 ViewChild 方法获取对按钮的引用,然后使用其 nativeElement
属性.
import { Component, ViewChild } from '@angular/core';
@Component({
selector: 'my-app',
template: `<h1>My First Angular 2 App</h1>
<button #myButton (click)="onClicked()">Click me!</button>`
})
export class AppComponent {
@ViewChild('myButton') button;
onClicked() {
this.button.nativeElement.disabled = true;
}
}
然而,Angular2 recommends using ElementRef's as a last resort. The same functionality you desire can be achieved through property binding.
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: `<h1>My First Angular 2 App</h1>
<button [disabled]="isDisabled" (click)="onClicked()">Click me!</button>`
})
export class AppComponent {
private isDisabled = false;
onClicked() {
this.isDisabled = true;
}
}
我正在尝试在单击按钮时将其禁用。通过单击我正在调用一个函数,我想禁用使用该函数的按钮。如何使用 ElementRef 访问按钮的 属性 并禁用它?我不是很熟悉如何使用 ElementRef。 任何帮助将不胜感激!
如果您真的想通过 ElementRef 禁用按钮,您可以使用 ViewChild 方法获取对按钮的引用,然后使用其 nativeElement
属性.
import { Component, ViewChild } from '@angular/core';
@Component({
selector: 'my-app',
template: `<h1>My First Angular 2 App</h1>
<button #myButton (click)="onClicked()">Click me!</button>`
})
export class AppComponent {
@ViewChild('myButton') button;
onClicked() {
this.button.nativeElement.disabled = true;
}
}
然而,Angular2 recommends using ElementRef's as a last resort. The same functionality you desire can be achieved through property binding.
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: `<h1>My First Angular 2 App</h1>
<button [disabled]="isDisabled" (click)="onClicked()">Click me!</button>`
})
export class AppComponent {
private isDisabled = false;
onClicked() {
this.isDisabled = true;
}
}