1

I have Angular 6.0.0 application. Need to dynamically append classes to html elements. Ideally, this should be implemented via directive. Currently I have something like this and it works OK.

<div class="class1 prefix-{{variable}}"></div>

I want to make the prefix reusable and I am trying to reach the better result by using a directive:

html:

<div class="class1" [appendBusinessLogicClass]="variable"></div>

appendBusinessLogicClass.directive.ts:

export class AppendBusinessLogicClass {
readonly prefix = 'prefix';
  @HostBinding('class') class = ''; // this clears the html class1
  @Input('appendBusinessLogicClass') set appendBusinessLogicClass(variable: string) {
      this.class = this.prefix + '-' + variable;
   }
}

But the HostBinding CLEARS class1 in the html code. But I'd like to APPEND 'prefix-rand' to the class list. Note, that we do not know variable at the compile time.

Thanks

4

1 回答 1

2

你现在实际上在做的是绑定到 class 属性,所以基本上值将是setto this.class,这完全没问题。但是,事实证明您实际上并没有从“类”属性中获取初始值,这意味着无论您class在模板上设置什么,该值都会被覆盖。所以基本上 Angular 正在接管设置该class属性。

因此,您要做的就是在class属性中获取该值的引用。在 Angular 中,您实际上可以将任何html属性视为组件/指令的输入,您唯一需要做的就是使用@Input装饰器对其进行注释。在这里,我们将 class属性的值保存到defaultClassList,然后使用它来计算新的class属性值,因此您的代码可能如下所示:

export class AppendBusinessLogicClass {
    readonly prefix = 'prefix';

    @Input('class')
    defaultClassList;// `class` is a keyword so we're calling it defaultClassList instead

    @HostBinding('class')
    classList;// `class` is a keyword so we're calling it classList instead

    @Input('appendBusinessLogicClass') set appendBusinessLogicClass(variable: string) {
        this.classList = this.defaultClassList + " " + this.prefix + '-' + variable;
    }
}

this.classList总而言之,只要设置了传递给指令的值,您最终会获得模板中定义的属性值并将其包含在绑定中。

于 2018-05-22T15:36:58.150 回答