【问题标题】:Angular Material bind button type dynamicallyAngular Material 动态绑定按钮类型
【发布时间】:2021-02-11 03:36:25
【问题描述】:

我在我的项目中使用 Angular Material。我想根据变量动态设置按钮类型。我尝试了类似以下的方法:

export class ButtonComponent {
  type: 'simple' | 'raised' | 'stroked' | 'flat' | 'icon' | 'fab' | 'mini-fab' = 'simple";
}

在 HTML 中

<button [mat-button]="type === 'simple'" [mat-raised-button]="type === 'raised'">
  Text goes here 
</button>

但我收到以下错误:

无法绑定到“mat-button”,因为它不是“button”的已知属性

虽然我在 module.ts 中导入了 MatButtonModule

感谢您抽出宝贵时间,并提前感谢大家。

【问题讨论】:

    标签: angular button angular-material


    【解决方案1】:

    您需要将 MatButtonModule 导入到包含您的组件的模块中:

    import {MatButtonModule} from '@angular/material/button';

    如果你想动态应用元素属性,你可以这样做:

    <button [attr['mat-button']]="type === 'simple' ? '' : null">
      Text goes here 
    </button>
    

    【讨论】:

    • 它对我有用,但在将其更改为以下内容后:
    • 该属性是一个指令。当它被应用时,它会做它应该对宿主元素做的事情(例如应用样式)。除了您在问题中描述的内容之外,我真的不知道您需要什么。
    • 您可能需要创建一个带有属性的&lt;button&gt;。因为如果 DOM 中已经有一个按钮没有应用指令,而您稍后再应用它,它将只是一个属性(指令中的代码不会被执行)。所以用**ngIf包裹按钮并将按钮放在里面
    猜你喜欢
    • 1970-01-01
    • 2018-12-10
    • 2019-04-21
    • 1970-01-01
    • 2015-07-05
    • 1970-01-01
    • 2013-06-07
    • 1970-01-01
    • 2019-05-01
    相关资源
    最近更新 更多