Angular Material 动态绑定按钮类型

4
我在我的项目中使用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。

感谢您的时间,提前感谢您的帮助。

3个回答

4

针对 Angular Material >= 15

我准备了一个组件,根据给定的参数渲染 mat 按钮。您可以从可用的材料调色板中指定类型和颜色。

my-button.component.html:

<button
  mat-button
  [disabled]="disabled"
  [color]="color"
  [ngClass]="{
    'mat-mdc-button mat-mdc-raised-button': type === 'raised',
    'mdc-button--outlined mat-mdc-outlined-button': type === 'stroked',
    'mat-mdc-unelevated-button': type === 'flat',
    'mat-mdc-menu-item mdc-list-item': type === 'menu'
  }"
>
  <span>{{ text }}</span>
</button>

my-button.component.ts:

import { Component, EventEmitter, Input, Output } from '@angular/core';

@Component({
  selector: 'app-my-button',
  templateUrl: './my-button.component.html'
})
export class MyButtonComponent {
  @Input() text: string = "";
  @Input() disabled: boolean = false;
  @Input() color: 'primary' | 'accent' | 'warn' = 'primary';
  @Input() type: 'raised' | 'stroked' | 'flat' | 'menu' = 'raised';

  @Output() click: EventEmitter<void> = new EventEmitter<void>();
}

最后用法:

<app-my-button
  text="Click me!"
  color="warn"
  type="stroked"
></app-my-button>

希望它能对你有所帮助!


1

您需要在包含组件的模块中导入 MatButtonModule

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

然后,如果您想要动态应用元素属性,可以使用以下方法:

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

它在我这里起作用,但在将其更改为以下内容后:<button [attr.mat-button]="type === 'simple' ? '' : null"> 文本放在这里 </button>使用这种方法应用属性,但不幸的是,一些依赖于该属性的Angular Material类不能使用这种方式应用 =(. 但再次感谢您的答案。 - undefined
该属性是一个指令。当应用时,它会按照其应有的方式与宿主元素进行操作(例如应用样式)。除了你在问题中描述的内容,我真的不知道你还需要什么。 - undefined
你可能需要创建一个带有属性的<button>。因为如果DOM中已经有一个没有应用指令的按钮,而你后来再应用指令,它只会成为一个属性(指令中的代码不会被执行)。所以用**ngIf包裹按钮,并将按钮放在其中。 - undefined

0

我通过 ngClass 完成了这项工作:

<button [ngClass]="{
  'mat-button': type === 'simple',
  'mat-raised-button': type === 'raised'
}">Text goes here</button>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接