我正在尝试在单击时禁用按钮.通过单击我正在调用一个函数,我想要使用该函数禁用该按钮.如何使用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.您可以通过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;
- }
- }