Amar
Amar

Reputation: 529

Angular 2 Change text of HTML element

I want to change the text of a html element.

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
    }

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

Upvotes: 12

Views: 21803

Answers (2)

FAISAL
FAISAL

Reputation: 34683

Use interpolation using the double curly braces {{ }} and bind your FirstName and LastName. Read more about template syntax.

Change your html to following:

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

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

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

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

Upvotes: 13

Anup pandey
Anup pandey

Reputation: 437

Step 1:-At html file (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)

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

Upvotes: 0

Related Questions