【问题标题】:Angular 2 Change text of HTML elementAngular 2更改HTML元素的文本
【发布时间】:2018-03-06 04:06:11
【问题描述】:

我想更改 html 元素的文本。

profile.component.html

<div class="col col-sm-12">
  <h2>FirstName LastName</h2>
</div>

profile.component.ts

changeName():void{
        //Code to change the <h2> element
    }

如果你能提供代码示例如何做到这一点,那就太好了!

【问题讨论】:

标签: html angular typescript


【解决方案1】:

使用interpolation 和双花括号{{ }} 并绑定你的FirstNameLastName。阅读有关template syntax 的更多信息。

将您的 html 更改为以下内容:

<div class="col col-sm-12">
  <h2>{{ FirstName }} {{ LastName }}</h2>
</div>

...在你的profile.component.ts

FirstName: string = '';
LastName: string = '';

changeName():void{
    this.FirstName = 'New First Name';
    this.LastName = 'New Last Name';
}

【讨论】:

    【解决方案2】:

    第1步:-在html文件(profile.component.html)

    <div class="col col-sm-12">
      <h2 *ngIf="data==null; else elseBlock" >FirstName LastName</h2>
    <ng-template #elseBlock><h2  [innerHTML] = "data"></h2></ng-template>
    </div>
    

    第2步:在ts文件(profile.component.ts)

    public data:any;
    changeName():void{
           this.data="Your Data";
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-20
      • 1970-01-01
      • 2019-07-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多