来自组件的Angular 2+ Attach指令动态

时间:2018-07-06 23:31:35

标签: angular angular-directive angular-components

我需要根据某些条件从组件附加指令。 我试图像这样通过@HostBinding来做到这一点,但是它不起作用

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

 @Component({
   selector: 'my-app',
   template: `
     <div>Test text</div>
   `
 })
 export class AppComponent  {
    @HostBinding('attr.appCustomDirective') directive;
 }

 @Directive({
   selector: '[appCustomDirective]'
 })
 export class CustomDirective {
   @HostBinding('style.color') color = 'red';
 } 

我认为我需要重新编译模板或类似的东西,但是我不知道该怎么做。

将非常感谢您的帮助!

Code snippet on stackblitz

1 个答案:

答案 0 :(得分:0)

您几乎完成了所有正确的操作,只需将指令添加到要应用样式的宿主元素。您不能动态添加或删除指令(至少到目前为止),但是您可以做的一件事是通过@Input()变量禁用或启用指令,并且可以在主机绑定的getter上进行检查。

import { Component, Directive, HostBinding, HostListener, Input, OnChanges, SimpleChanges, SimpleChange } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
    <div appCustomDirective [enabled-directive]="isDirectiveEnabled">Test text</div>
        <button (click)="enableDirective()">Enable</button>
  `,
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  isDirectiveEnabled: boolean;
  constructor() {
    this.isDirectiveEnabled = true;
  }

  @HostBinding('attr.appCustomDirective') directive;

  enableDirective() {
    this.isDirectiveEnabled = !this.isDirectiveEnabled;
  }
}

@Directive({
  selector: '[appCustomDirective]'
})
export class CustomDirective {
  @Input('enabled-directive') enabledDirective: boolean;
  @HostBinding('style.color') color : string;

  ngOnChanges(changes: SimpleChanges) {
    const directiveState: SimpleChange = changes.enabledDirective;
    this.color = directiveState.currentValue ? 'red' : 'black';
  }


}

看看工作中的堆叠here