【问题标题】:simple directive to add class doesn't work添加类的简单指令不起作用
【发布时间】:2022-01-06 08:44:47
【问题描述】:

我想根据两个条件向div 添加一个类。为此,我创建了一个这样的指令:

import { Directive, HostBinding, Input } from '@angular/core';

@Directive({
  selector: '[confirmdialog-style]',
})
export class ConfirmDialogStyleDirective {
  @Input() isMsgDialog!: boolean;
  @Input() dialogType!: string;

  @HostBinding('class')
  elementClass = this.isMsgDialog ? 'x-' + this.dialogType : '';
}

我是这样使用它的:

<div
  class="x-dialog-container"
  confirmdialog-style
  [isMsgDialog]="isMsgDialog"
  [dialogType]="dialogType"
>

我通过按钮单击在父组件中设置了isMsgDialogdialogType 属性。我通过 chrome 调试工具检查了这两个输入属性设置正确。

问题是,所需的类(例如x-danger)未添加到div。为什么这不起作用?

【问题讨论】:

    标签: angular typescript angular-directive


    【解决方案1】:

    试试这个,让它考虑isMsgDialogdialogType的变化:

        @HostBinding('class')
        get elementClass() {
            return this.isMsgDialog ? 'x-' + this.dialogType : '';
        }
    

    【讨论】:

    • 谢谢,成功了。
    【解决方案2】:

    我发现你的代码很好,我认为有必要验证 isMsgDialog 不为空

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多