Angular 2 ContentChild未定义

编程入门 行业动态 更新时间:2024-10-26 00:26:14
本文介绍了Angular 2 ContentChild未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我试图获取一个元素的ElementRef,该元素已使用指令作为组件的ContentChild添加了自定义属性,但是在初始化内容后对其进行记录时我未定义.你能告诉我为什么吗?

I am trying to get the ElementRef of an element on which I have added a custom attribute using a Directive as a ContentChild of a component but I get undefined when I log it after the content has been initialized. Could you please tell me why?

TestComponent:

TestComponent:

@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); } }

TestDirective:

TestDirective:

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

AppComponent:

AppComponent:

@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: plnkr.co/edit/9KUnFWjVIbYidUtF2Avf?p=预览

Please refer to think Plunk: plnkr.co/edit/9KUnFWjVIbYidUtF2Avf?p=preview

推荐答案

您错过了 TestDirective 的声明!

查看更新后的监听器: plnkr.co/edit/x5rLcvJnRhnVxM7fgvvK?p=preview

See your updated plunker: 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 './appponent'; import { TestComponent } from './testponent'; import { TestDirective } from './test.directive'; @NgModule({ imports: [ BrowserModule, FormsModule, HttpModule, ], declarations: [ AppComponent, TestComponent, TestDirective ], bootstrap: [ AppComponent ] }) export class AppModule { }

更多推荐

Angular 2 ContentChild未定义

本文发布于:2023-11-22 23:21:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1619312.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:未定义   Angular   ContentChild

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!