【发布时间】:2018-02-07 09:52:27
【问题描述】:
我正在尝试构建一个结构指令,该指令将通过使用其选择器(静态)或调用其公共方法(动态)来更改父 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 结构。
** 如有错别字请忽略。抱歉,我无法在此处粘贴完整的代码
【问题讨论】:
-
模板中没有该指令是不可能的。你想要的是一个辅助方法/类而不是指令。
-
你能给我举个例子吗?
标签: angular angular-directive angular-components