Reputation: 769
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.
Upvotes: 7
Views: 26979
Reputation: 2546
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.
Upvotes: 3
Reputation: 14395
<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
Upvotes: 21