Search code examples
angularangular-materialiconsinnerhtml

mat-icon element doesn't shows icon text instead of icon shape when I use innerHtml in angular


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?


Solution

  • 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.