我正在尝试构建一个结构指令,它将更改通过使用其选择器(静态)或通过调用其公共(public)方法(动态)调用的父 DOM 结构。
在 html 模板中使用指令选择器可以正常工作 任何问题。
我想弄清楚我们是否可以在不在模板中使用它并通过调用指令方法的情况下实现相同的效果。
我的指令.ts
@Directive({ selector: '[sampleDirective]' })
export class SampleDirective {
...
constructor(..) {
this.customDirective();
}
}
customDirective() {
console.log('Inside customDirective()');
}
我的组件.ts
import { SampleDirective } from './my.directive';
...
@Component({
selector: 'my-component',
template: `<button (click)="click()"> Click Me </button>`
})
constructor() { }
..
click() {
// call directive method here
}
我需要这个,因为我正在创建一个通用解决方案,以在运行时借助指令更改组件的 DOM 结构。
** 如有错字请忽略。抱歉,我不能在这里粘贴完整的代码
最佳答案
如果组件模板中没有指令,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
}
关于来自组件的 Angular 4 调用指令方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45947596/