Disabling a button by capturing ElementRef: angular2

I am trying to disable a button when pressed. By clicking "I call the function" and I want to disable this button using this function. How can I access a button property using ElementRef and disable it? I am not very familiar with how to use ElementRef. Any help would be greatly appreciated!

+6
source share
1 answer

If you really wanted to disable the button via ElementRef, you can use the ViewChild method to get a link to your button and then disable this button using the 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 as a last resort . You can achieve this functionality with property bindings .

 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; } } 
+6
source

All Articles