【发布时间】:2021-12-01 16:19:54
【问题描述】:
首先,抱歉,如果这是重复的。我一直在寻找一些答案,但没有找到。让我解释一下我的问题。
我有一个指令
@Directive({
selector: '[myOwnDirective]',
})
export class MyOwnDirective {
@Input() set myOwnDirective(value: string) {
// do Something
}
@Output() valueChange = new EventEmitter<any>();
constructor(private el: ElementRef) {}
// Some more logic which will at some moment trigger the EventEmitter
}
我想通过 hostBinding 将此指令注入自定义组件。
export class MyOwnComponent implements OnInit {
@HostBinding('attr.myOwnDirective') myOwnDirective = new MyOwnDirective(this.el);
constructor(private el: ElementRef){}
ngOnInit() {
this.myOwnDirective.myOwnDirective = 'someValue';
}
如您所见,在 ngOnInit 挂钩中,我可以设置指令中的 @Input 参数,就像我通常在 HTML 模板中使用 [] 所做的那样。 但是我如何能够捕获通过 EventEmitter 发出的值?
【问题讨论】:
-
为什么不想在 HTML 中使用默认方法?
-
我不能这样做,因为我必须使用该指令的地方之一是使用 ComponentFactoryResolver 呈现的,因此该元素无法在 HTML 模板中定位
标签: angular angular2-directives