Disabling a button by grabbing ElementRef: angular2

拈花ヽ惹草 提交于 2019-12-08 15:26:56

问题


I'm trying to disable a button when it is clicked. By clicking I'm calling a function and I want to disable the button using that function. How can I access button's property with ElementRef and disable it? I'm not very familiar with how to use ElementRef. Any help would be greatly appreciated!


回答1:


If you really wanted to disable the button via an ElementRef, you can use the ViewChild method to get a reference to your button and then set the button to disabled using its nativeElement property.

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;
  }
}

However, 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;
  }
}


来源:https://stackoverflow.com/questions/38035620/disabling-a-button-by-grabbing-elementref-angular2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!