Unable to change text of a Button in Angular

佐手、 提交于 2020-06-17 15:13:11

问题


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


回答1:


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"
    }
  }


来源:https://stackoverflow.com/questions/51714890/unable-to-change-text-of-a-button-in-angular

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!