Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disabling a button by grabbing ElementRef: angular2

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!

like image 534
Aiguo Avatar asked Jun 26 '16 05:06

Aiguo


People also ask

How to disable a button in Angular based on condition?

You can disable a button in angular after it clicked by bounding the button disabled property to a Boolean variable in the component.

How to make button disable in Angular?

You can enable or disable the ButtonGroup for Angular. By default, the component is enabled. To disable the whole group of buttons, set the disabled attribute of the ButtonGroup to true . To disable a specific button, set its own disabled attribute to true and leave the disabled attribute of the ButtonGroup undefined.


1 Answers

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;
  }
}
like image 151
Michael Avatar answered Oct 01 '22 23:10

Michael