只是想将一个字符串传递到组件输入中,这样我就可以拥有一个动态图标。这可能吗? 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>
最佳答案
您的代码大部分是正确的。
尽管您对 CSS 类进行数据绑定(bind)的方式破坏了 Material 图标字体,因为它删除了将文本转换为 svg 图标所需的原始类。
改变这个:
<mat-icon class="alert--{{context}}" *ngIf="icon">{{icon}}</mat-icon>
对此:
<mat-icon [className]="'mat-icon material-icons alert--'+context" *ngIf="icon">{{icon}}</mat-icon>
或首选:
<mat-icon [ngClass]="'alert--'+context" *ngIf="icon">{{icon}}</mat-icon>
ngClass
仅将给定的字符串附加到类属性,而 className
会覆盖它。
出于学习目的: 实际上还有一种绑定(bind)静态 CSS 类的方法,在我看来,这是最好的方法。
[class.myClass]="expression"
例如:
[class.myClass]="true"
会产生:
class="myClass"
关于angular - 如何将动态值传递给 matIcon?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51290105/