angular - 如何将动态值传递给 matIcon?

标签 angular angular-material

只是想将一个字符串传递到组件输入中,这样我就可以拥有一个动态图标。这可能吗? 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/

相关文章:

Angular Material 日期选择器最小和最大日期验证消息

angular - 更改 Angular Material 表中的行颜色

angular - 如何在“保存”按钮上单击 typescript 文件中获取 <mat-radio-group> 选定值

angular - 无法从 ionic2 Cordova InAppBrowser 插件启动 URL

angular - 使用IONIC Storage Service,如何获取和返回存储的JSON数据?

html - 即使在使用 CSS 添加列表元素后,修复图像右下角的位置

Angular2 Material Responsive Sidenav 和 flex-layout

javascript - Angular 2 外部 JS 库 Skycons

angular - 如何以 react 形式收听 AbstractControl 的 valueChanges 和 setValue

angular - startWith ('' ) typescript 代码有什么作用?