-1

I want to dynamically add mat-icon via innerHtml to my component but the result is icon text not icon shape.

here is my template variable:

edit_template = `
  <button mat-icon-button color="primary" (click)="clicked()">
    <mat-icon aria-label="Edit data">edit</mat-icon>
  </button>
`;

and here is innerHtml:

<table mat-table [dataSource]="this.dataSource">
  <div *ngFor="let displayedColumn of displayedColumns">
    <ng-container [matColumnDef]="displayedColumn">
      <th mat-header-cell *matHeaderCellDef> {{displayedColumn}} </th>
      <td mat-cell *matCellDef="let element" [innerHTML]="element[displayedColumn]"></td>
    </ng-container>
  </div>
</table>

And the result is edit word instead of edit icon!

in addition to mentioned problem, even edit word doesn't act as button but just as a text!

What's your idea?

Blue Moon
  • 411
  • 7
  • 20
  • 1
    You cannot inject Angular components or directives with `[innerHTML]`. See [this post](https://stackoverflow.com/q/38739439/1009922), and the linked one, for more details. – ConnorsFan Jul 16 '19 at 21:16

2 Answers2

1

use this way , you dont need to edit the HTML

<mat-icon>{{element[displayedColumn]}}</mat-icon>

dota2pro
  • 7,220
  • 7
  • 44
  • 79
  • `element[displayedColumn]` is general purpose variable and I have values other than mat-icon. may be I should separate those elements and define specific format for them. but I don't like such thing. It's better all values shows correctly with less coding. – Blue Moon Jul 16 '19 at 21:01
-1

finally I made it!

here is my solution:

modify definition:

edit_template = `edit`;

and in the html file I used ngIf:

<table mat-table [dataSource]="this.dataSource">
  <div *ngFor="let displayedColumn of displayedColumns">
    <ng-container [matColumnDef]="displayedColumn">
      <th mat-header-cell *matHeaderCellDef> {{displayedColumn}} </th>
      <td mat-cell *matCellDef="let element">
          <div *ngIf="element[displayedColumn] === 'edit' || element[displayedColumn] === 'delete';then content else other_content">here is ignored</div>
          <ng-template #content>
            <button mat-icon-button color="primary">
              <mat-icon>{{element[displayedColumn]}} </mat-icon>
            </button>
          </ng-template>
          <ng-template #other_content>{{element[displayedColumn]}} </ng-template>
      </td>
    </ng-container>
  </div>
</table>

and the result is as I expect.

Blue Moon
  • 411
  • 7
  • 20