【问题标题】:Add a class to directive in angular在角度指令中添加一个类
【发布时间】:2021-12-06 03:06:36
【问题描述】:

我有一个简单的指令,我想给它添加一个类:

@Directive({
  selector: '[appFieldLabel]',
})
export class FieldLabelDirective {
  @Input() tooltip: string;
  @Input() showOptional = true;

  @HostBinding('class.text-truncate')
  test = true;
}

这可行,但我希望它始终被设置,有没有办法不分配像这里test = true;这样的无用属性

谢谢

【问题讨论】:

标签: angular class


【解决方案1】:

您可以绑定到class 而不是prop = true,然后将值设置为您想要的类,如下所示:

@Directive({
  selector: '[appFieldLabel]',
})
export class FieldLabelDirective {
  @Input() tooltip: string;
  @Input() showOptional = true;

  @HostBinding('class') private hostClass = 'text-truncate';
}

没那么没用,因为你可以通过变量修改类。

你也可以像这样绑定类:

@Directive({
  selector: '[appFieldLabel]',
  host: {
    'class': 'text-truncate',
  }
})
export class FieldLabelDirective {
  // the rest of the code
}

【讨论】:

  • 第二个选项告诉我已弃用,我猜我会做第一个
  • 您使用哪个版本的 Angular?
  • 我使用 12。无论如何,我选择了你的第一个解决方案。
  • 我可能是错的,但我查看了官方文档并没有关于弃用的消息。我还检查了我的机器并且 eslint 没有抱怨。我想这可能与您的 eslint/tslint 配置有关。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-10
  • 2017-09-04
  • 1970-01-01
  • 1970-01-01
  • 2020-08-22
相关资源
最近更新 更多