gpt4 book ai didi

Angular2 - 来自指令的 ViewChild

转载 作者:太空狗 更新时间:2023-10-29 17:13:56 27 4
gpt4 key购买 nike

我有一个名为 EasyBoxComponent 的组件,和一个带有此 @Viewchild@Directive:

@ViewChild(EasyBoxComponent) myComponent: EasyBoxComponent;

我认为这是正确的语法,但 this.myComponent 始终未定义。


完整代码如下:

<my-easybox></my-easybox>
<p myEasyBox data-href="URL">My Directive</p>
import { Directive, AfterViewInit, HostListener, ContentChild } from '@angular/core';
import { EasyBoxComponent } from '../_components/easybox.component';

@Directive({
selector: '[myEasyBox]'
})
export class EasyBoxDirective implements AfterViewInit {

@ContentChild(EasyBoxComponent) myComponent: EasyBoxComponent;
@ContentChild(EasyBoxComponent) allMyCustomDirectives;

constructor() {
}

ngAfterViewInit() {
console.log('ViewChild');
console.log(this.myComponent);
}

@HostListener('click', ['$event'])
onClick(e) {
console.log(e);
console.log(e.altKey);
console.log(this.myComponent);
console.log(this.allMyCustomDirectives);
}
}

最佳答案

ContentChild 使用 AfterContentInit 接口(interface),所以模板应该是这样的:

<p myEasyBox data-href="URL">
<my-easybox></my-easybox>
</p>

@Directive:

@Directive({
selector: '[myEasyBox]'
})
export class EasyBoxDirective implements AfterContentInit {
@ContentChild(EasyBoxComponent) myComponent: EasyBoxComponent;
@ContentChild(EasyBoxComponent) allMyCustomDirectives;

ngAfterContentInit(): void {
console.log('ngAfterContentInit');
console.log(this.myComponent);
}

constructor() {
}

@HostListener('click', ['$event'])
onClick(e) {
console.log(e);
console.log(e.altKey);
console.log(this.myComponent);
console.log(this.allMyCustomDirectives);
}
}

关于Angular2 - 来自指令的 ViewChild,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43271394/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com