Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change button text and disable button on click event in angular2

How do you change the text of a <button> when that button is clicked in angular2?

For example, changing the button text from "Save" to "Saving..." and then also set it to be disabled.

I know how to do this in AngularJS, jQuery, and plain JS, and I have some ideas on how to do this in Angular2, but I wanted to make sure I'm not doing it in some outdated or convoluted way when it comes to Angular2.

like image 681
mkimmet Avatar asked Jan 05 '17 15:01

mkimmet


People also ask

How do I change the text on a clicked button?

To change the text of a button on click: Add a click event listener to the button. Use the textContent property to change the button's text. For example, btn. textContent = 'Button clicked' .

How do I block a button click event?

To disable the click event in HTML, the “pointer-events” property of CSS is used. For this purpose, add an HTML element and set the value of the pointer-events property as “none” to disable its click event.

How to disable button in angular based on condition?

How do you disable a button in angular 6 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 disable a button in angular ts?

Button component can be enabled/disabled by giving disabled property. To disable Button component, the disabled property can be set as true .


2 Answers

<button (click)="setSaving($event.target, 'saving')">save</button>

and then in your component:

setSaving(element, text){
  element.textContent = text;
  element.disabled = true;
}

You can also set the properties using the Renderer

like image 93
Meir Avatar answered Oct 08 '22 15:10

Meir


Here's an example for asynchronous calls that worked for me:

Template:

<button (click)="loadMore($event.target)">load more</button>

Component (pseudocode):

export class MyComponent{

    button;

    constructor(private _apiService: ApiService){}

    ngOnInit()
    {
        this.load();
    }

    load()
    {
        this._apiService
            .getAsyncFrom( '/sample/url' )
            .subscribe(data=> {

                // do something with your data

                // enable it
                if(this.button)
                {
                    this.button.textContent = 'load more';
                    this.button.disabled=false;
                }
            });
    }

    loadMore(element)
    {    
        // assign to class
        this.button = element;

        //disable it
        this.button.textContent = 'loading...';
        this.button.disabled=true;

        this.load();
    }
}

Basically assign the element to the class and access it where you need it.

like image 25
angelcool.net Avatar answered Oct 08 '22 13:10

angelcool.net