无法在Angular中更改按钮的文本 [英] Unable to change text of a Button in Angular

查看:330
本文介绍了无法在Angular中更改按钮的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的模板具有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")
    }
  }

我也尝试过renderer.setProperty,但是那也不起作用.

I tried renderer.setProperty as well but that didn't work either.

我总是在按钮上看到Show Template

推荐答案

您要在<button>中更改的值不是来自value属性,而是来自按钮标记之间的测试.要更改它,它比您想的要容易,您所要做的就是为要更改的值设置一个文本,然后将其放在HTML的插值中.
代码:

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>


另外,您甚至不需要一个变量,只需执行以下操作即可:


Plus, you dont even need a variable for that, you can simply do:

<button value="Show Template" #btn (click)="showTemplate(btn)">{{btn.value}}</button>

并在您的代码中:

showTemplate(btn){
    this.showTmpl=!this.showTmpl;
    if(this.showTmpl){
      btn.value = "Hide Template"
    } else {
      btn.value = "Show Template"
    }
  }

这篇关于无法在Angular中更改按钮的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆