typescript Angular 2 更改 HTML 元素的文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46400934/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:55:12  来源:igfitidea点击:

Angular 2 Change text of HTML element

htmlangulartypescript

提问by Amar

I want to change the text of a htmlelement.

我想更改html元素的文本。

profile.component.html

配置文件.component.html

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

profile.component.ts

profile.component.ts

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

If you could provide code example how to do this, it would be good!.

如果您能提供如何执行此操作的代码示例,那就太好了!

采纳答案by Faisal

Use interpolationusing the double curly braces {{ }}and bind your FirstNameand LastName. Read more about template syntax.

使用双花括号进行插值{{ }}并绑定您的FirstNameLastName。阅读有关模板语法的更多信息。

Change your html to following:

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

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

... and in your profile.component.ts:

...并在您的profile.component.ts

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

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

回答by Anup pandey

Step 1:-At html file (profile.component.html)

第 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>

Step 2: At ts file (profile.component.ts)

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

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