gpt4 book ai didi

Angular 2 ContentChild 未定义

转载 作者:行者123 更新时间:2023-12-05 03:10:29 25 4
gpt4 key购买 nike

我正在尝试获取一个元素的 ElementRef,我在该元素上使用 Directive 作为组件的 ContentChild 添加了自定义属性,但在内容初始化后记录它时我得到了 undefined。你能告诉我为什么吗?

测试组件:

@Component({
selector: 'test-component',

template: `
<h1>Test Component</h1>
<ng-content></ng-content>
`
})
export class TestComponent implements AfterContentInit {
@ContentChild(TestDirective) child;

ngAfterContentInit() {
console.log(this.child);
}
}

测试指令:

@Directive({
selector: '[test-directive]'
})
export class TestDirective {
}

应用组件:

@Component({
selector: 'my-app',
declarations: ['TestComponent'],
template: `
<h1>{{title}}</h1>
<test-component>
<h2 test-directive>Test Directive</h2>
</test-component>
`
})
export class AppComponent {
title = 'Hello123!';
}

请引用think Plunk:https://plnkr.co/edit/9KUnFWjVIbYidUtF2Avf?p=preview

最佳答案

您错过了TestDirective声明!

查看更新后的插件:https://plnkr.co/edit/x5rLcvJnRhnVxM7fgvvK?p=preview

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { TestComponent } from './test.component';
import { TestDirective } from './test.directive';

@NgModule({
imports: [
BrowserModule,
FormsModule,
HttpModule,
],
declarations: [
AppComponent,
TestComponent,
TestDirective
],
bootstrap: [ AppComponent ]
})
export class AppModule {
}

关于Angular 2 ContentChild 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39598072/

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