Angular 6 HostBinding 具有多个值?

问题描述 投票:0回答:3

我已在 Angular 6 应用程序中成功使用

@HostBinding
将属性应用到主机组件,就像在变量为 true 时应用类一样:

@HostBinding('class.compact-ui') isCompact;

但是现在,我需要根据选择菜单的模型分配 4 个可能的类之一。例如,用户可以

red
blue
green

我想当任何颜色为真时我可以使用多个主机绑定:

@HostBinding('class.green-ui') uiColor === 'green';

但这似乎是错误的。正确的方法是什么?

angular angular-components angular2-hostbinding
3个回答
6
投票

要将多个班级分配给主机,您可以执行以下操作:

@HostBinding('class') classAttribute: string = 'classA classB';

对于你的情况,你可以这样做:

@HostBinding('class') classAttribute: string;

// Example function that updates the classAttribute property
// You might handle it differently in your application
updateClassAttribute(color: string, isCompact: boolean) {
  const classes: string[] = [`${color}-ui`];

  if (isCompact) classes.push('compact-ui');

  this.classAttribute = classes.join(' ');
}

注意,上面的函数逻辑可以写成一行,如下所示:

this.classAttribute = [ ...isCompact ? ['compact-ui'] : [], `${color}-ui` ].join(' ');

此外,如果您在应用程序中的多个位置需要这些值(

@ngrx/store
isCompact
),您可以考虑使用 Redux 存储(例如
color
)。


4
投票

注意:这适用于最新版本的 Angular,可能不适用于旧版本(根据问题标题)。

还可以返回一个对象,该对象会将所有

true
值添加到元素并从元素中删除所有
false
值。

  /** The size of the button. */
  @Input() size: ButtonSize = 'md';

  /** The classes to attach to the element. */
  @HostBinding('class')
  get elementClasses() {
    return {
      'primary-button': true,
      [`primary-button--${this.size}`]: true,
      'primary-button--color': false,
      'other-class': this.isOtherClass()
    }
  }

1
投票

你也可以有风格地做到:

@HostBinding('style')
get style_binding()
{
    return { 
        display: 'grid',
        gap: this.config.internalGap,
        margin: this.config.margin,
        gridArea: this.config.area
    };
}
© www.soinside.com 2019 - 2024. All rights reserved.