7

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.

0

2 Answers 2

21
<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

Sign up to request clarification or add additional context in comments.

1 Comment

thanks, cleaner than my ideas. One thing, you had element.attributes.disabled = true, which didn't seem to work for me, however, element.disabled = true did work. I've edited your post to reflect that.
3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.