首页 > 解决方案 > 传递给 ngclass 枚举字符串值

问题描述

我创建了一个enum来组织我的新组件样式,我需要编写多个 ng 类表达式或直接动态传递给元素调用。如何直接调用元素?

按钮类型.ts

export enum ButtonTypes {
   Primary = 'button-primary',
   Secondary = 'button-secondary',
   Terciary = 'button-terciary',
   IconButton = 'button-icon',
}

bo-button.component.html

<button [ngClass]="type">
  <i [ngClass]="icon"></i>
  {{ label }}
</button>

bo-button.componrny

import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { ButtonTypes } from './shared/button-types';

@Component({
  selector: 'lib-bo-button',
  templateUrl: './bo-button.component.html',
  styleUrls: ['./bo-button.component.scss']
})   

export class ButtonComponent implements OnInit {
  @Input() public type: ButtonTypes;
  @Input() public icon: string;
  @Input() public label: string;
  @Input() public arrow: string;

  constructor() {
  }    
  ngOnInit() {
  }    
}

标签: angulartypescript

解决方案


如果将ButtonTypes枚举定义分配给父组件的属性,则可以在模板中使用该属性与文字枚举值进行数据绑定。具有枚举值的属性的数据绑定也可以工作,如下myButtonType例所示。

import { ButtonTypes } from './button-types.enum';
...
export class AppComponent {

  ButtonTypes = ButtonTypes;             // <-- Allows to use enum literals in template
  myButtonType = ButtonTypes.Secondary;  // <-- Specific enum value for binding
}
<lib-bo-button [type]="ButtonTypes.Terciary" label="My terciary button"></lib-bo-button>
<lib-bo-button [type]="myButtonType" label="My button"></lib-bo-button>

将应用适当的类样式,假设它是为每个ButtonTypes值定义的:

button.button-primary {
  background-color: dodgerblue;
}

button.button-secondary {
  background-color: green;
}

button.button-terciary {
  background-color: fuchsia;
}

button.button-icon {
  background-color: red;
}

请参阅此 stackblitz以获取演示。


推荐阅读