Angular 4 从组件调用指令方法

Angular 4 call directive method from component

我正在尝试构建一个结构指令,它将更改通过使用其选择器(静态)或通过调用其 public 方法(动态)调用的父 DOM 结构。

我的-directive.ts

@Directive({ selector: '[sampleDirective]' })

export class SampleDirective {
    ...
   constructor(..) {
        this.customDirective();
     }
  }
customDirective() {
    console.log('Inside customDirective()');
}

我的-component.ts

import { SampleDirective } from './my.directive';
...
@Component({
 selector: 'my-component',
 template: `<button (click)="click()"> Click Me </button>`
})
constructor() { }
..
click() {
  // call directive method here
}

我需要这个,因为我正在创建一个通用解决方案,以在指令的帮助下在运行时更改组件的 DOM 结构。

** 如有错字请忽略。抱歉,我无法在此处粘贴完整代码

要从组件调用指令方法,您可以使用 ViewChild 装饰器在页面上定位指令实例。然后通过使用相同的方法,您可以访问所有道具的指令。

@ViewChild(SampleDirective) directive;
constructor() { }
..
click() {
  // call directive method here
  this.directive.customDirective()
}

如果组件模板中没有指令 Angular 将不会处理它。使用 ng-container 标签,您不会以任何方式使模板混乱。要获取指令,请使用 @ViewChildren/@ViewChild 获取指令的实例:

@Component({
 selector: 'my-component',
 template: `<button (click)="click()"> Click Me </button>
            <ng-container sampleDirective></ng-container>`
})
@ViewChildren(SampleDirective) dirs;
constructor() { }
..
click() {
   this.dirs.first.customDirective();
  // call directive method here
}