Reputation: 16729
My template has a button
<button #showTmplButton (click)="showTemplate()">Show Template </button>
I am getting reference of the button in the component's class and I want to toggle the text of the button but I am unable to do so. What am I doing wrong?
@ViewChild("showTmplButton") showTmplButton:ElementRef;
showTmpl:boolean=false;
constructor(private renderer:Renderer2, hostElementRef:ElementRef){
}
showTemplate(){
this.showTmpl=!this.showTmpl;
if(this.showTmpl){
this.renderer.setAttribute(this.showTmplButton.nativeElement,"value","Hide Template")
} else {
this.renderer.setAttribute(this.showTmplButton.nativeElement,"value","Show Template")
}
}
I tried renderer.setProperty
as well but that didn't work either.
I always see Show Template
on the button
Upvotes: 0
Views: 2249
Reputation: 2290
The value that you are trying to change in the <button>
does not come from the value attribute, but from the test between the button tags. To change it, it is easier than you think, all you have to do is set a text for the value you want to change and just put it inside interpolation in the HTML.
CODE:
valueOfButton = "Show Template";
showTemplate(){
this.showTmpl=!this.showTmpl;
if(this.showTmpl){
this.valueOfButton = "Hide Template"
} else {
this.valueOfButton = "Show Template"
}
}
HTML:
<button (click)="showTemplate()">{{valueOfButton}}</button>
EDIT:
Plus, you dont even need a variable for that, you can simply do:
<button value="Show Template" #btn (click)="showTemplate(btn)">{{btn.value}}</button>
and in your code:
showTemplate(btn){
this.showTmpl=!this.showTmpl;
if(this.showTmpl){
btn.value = "Hide Template"
} else {
btn.value = "Show Template"
}
}
Upvotes: 4