简体   繁体   中英

How to update dynamic text using innerHtml with Angular 5 and Material Design

I have a list with dynamic data and I want to update a specific text when the user clicks on a button :

<mat-list> 
    <mat-list-item *ngFor="let id of ids">
      <mat-radio-group>
        <mat-radio-button name="car" value="honda" id="honda{{id}}" (change)="onChangeCar(id,honda)">Honda</mat-radio-button>
        <mat-radio-button name="car" value="toyota" id="toyota{{id}}" (change)="onChangeCar(id,toyota)">Toyota</mat-radio-button>
      </mat-radio-group>
   </mat-list-item>
<span [id]="id">Text to update</span>
</mat-list>

How to update the text dynamically in an Angular way? I know how to do it with the old fashion way but it's not suggested :

onChangeCar(id) {
  (<HTMLInputElement>document.getElementById(id)).innerHTML = "new text at a 
  specific Id";
}

replace

<span [id]="id">Text to update</span> 

with

<span >{{newVal}}</span>

and in your component create a variable to bind with newVal

Late reply, but you can simply add a content modifier to your element, such as:

<span [innerHTML]="carName"></span>

And in your code have update a class variable such as this:

public carName: string;

onChangeCar(newName) { 
   this.carName = newName;
}

This way, the text of the element will become whatever you set the variable carName has been set to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM