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>
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With