我正在尝试构建一个结构指令,该指令将通过使用其选择器(静态)或调用其公共方法(Dynamic)来更改父dom结构。
-
使用HTML模板中的指示选择器在没有的情况下工作正常任何问题。
-
我正在尝试弄清楚我们是否在不使用模板中使用并调用指令方法的情况下实现了同样的目标。
my-directive.ts
@Directive({ selector: '[sampleDirective]' })
export class SampleDirective {
...
constructor(..) {
this.customDirective();
}
}
customDirective() {
console.log('Inside customDirective()');
}
my-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结构。
** 如果有任何错字,请忽略。抱歉,我无法在此处粘贴完整的代码
如果组件模板中没有指令,则不会对其进行处理。使用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
}
用于从组件调用指令方法,您可以使用ViewChild
Decorator在页面上找到指令实例。然后,通过使用相同的方法,您可以访问指令所有道具。
@ViewChild(SampleDirective) directive;
constructor() { }
..
click() {
// call directive method here
this.directive.customDirective()
}