Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass a dynamic value to matIcon?

Just trying to pass a string into component input so I can have a dynamic icon. Is this possible? Stackblitz demo

@Component({
  selector: 'app-alert',
  template: `
    <mat-icon class="alert--{{context}}" *ngIf="icon">{{icon}}</mat-icon>
  `,
})
export class AlertComponent implements OnInit {
  @Input() context: string;

  @Input() icon: string;

  @Input() message: string;

  constructor() {}

  ngOnInit() {}
}
<mat-icon>home</mat-icon>
<app-alert [context]="'primary'" [icon]="'check'" [message]="'blah message working'"></app-alert>
like image 809
alphapilgrim Avatar asked Jul 11 '18 16:07

alphapilgrim


1 Answers

Your code is mostly right.

Though the way you databind the CSS class breaks the material icon font because it removes the original classes required to transform the text into an svg icon.

Change this:

<mat-icon class="alert--{{context}}" *ngIf="icon">{{icon}}</mat-icon>

To this:

<mat-icon [className]="'mat-icon material-icons alert--'+context" *ngIf="icon">{{icon}}</mat-icon>

Or prefered:

<mat-icon [ngClass]="'alert--'+context" *ngIf="icon">{{icon}}</mat-icon>

ngClass only appends the given string to the class attributes while className overrides it.


For learning purpose: There is actually one more way to bind a static CSS class, which is, in my opinion, the best.

[class.myClass]="expression"

ex :

[class.myClass]="true"

would produce:

class="myClass"
like image 140
Ploppy Avatar answered Sep 24 '22 14:09

Ploppy