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.
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' .
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 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.
Button component can be enabled/disabled by giving disabled property. To disable Button component, the disabled property can be set as true .
<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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With