I'm trying to get access to ng content with @ContentChild. To better understand @ContentChild I tried to implement a simple code example. I also did research such as here What's the difference between @ViewChild and @ContentChild?

还有更多的页面,但我已经坐在上面几个小时了,有以下问题.

如果我想在控制台中输出变量this.child,则会显示undefined.为什么会这样?我做错了什么?我需要做些什么不同的事情?

App-Root:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <应用程序-家长>
      <应用程序- children ></应用程序- children >
    </应用程序-家长>
  `
})
export class AppComponent {}

应用程序-家长

import { AfterContentInit, Component, ContentChild} from '@angular/core';
import { ChildComponent } from './child/child.component';

@Component({
  selector: '应用程序-家长',
  template: `
    <ng-content></ng-content>
  `
})
export class ParentComponent implements AfterContentInit {
  @ContentChild('refChild') child: any;

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

应用程序- children

import { Component} from '@angular/core';

@Component({
  selector: '应用程序- children ',
  template: `
    <div #refChild>
      <h1>Child headline</h1>
      <h2>Child subheadline</h2>
    </div>
  `
})

export class ChildComponent {}

Output

推荐答案

你几乎是对的...有一件事:ref分的正确位置直接放在子元素们的身上.

<app-parent>
  <app-child #refChild></app-child>
</app-parent>

那么它并不是更不确定:

enter image description here

对于另一个方向,您可以使用Services、EventEmitter或类似于Host的修饰符(它是子构造函数):

constructor(@Host() parent: ParentComponent) {
 console.log("Here it is", parent)
}

Angular相关问答推荐

如何在HTMLTITLE属性中使用Angular 显示特殊字符?

使用指令的 Angular 自定义验证在 ng-change 中无法正常工作

如何检测 Angular Universal 预渲染版本?

完成行为主体

RxJs 中的空闲可观察对象在幕后做了什么?

将 autoSpy 与 ng-mocks 一起使用时,如何重置 jasmine 间谍调用?

如何从父路由的组件访问激活的子路由的数据?

如何在对话框angular material内对齐按钮?

运行 npm 测试(Angular 2 单元测试)后无法读取未定义的属性 subscribe

如何在 Angular4 中访问组件的 nativeElement?

如何将新的 FormGroup 或 FormControl 添加到表单

Angular 4 - 在下拉列表中 Select 默认值 [Reactive Forms]

Angular 4.3拦截器不起作用

Angular 6在输入键上添加输入

在 RxJS Observable 中 flatten数组的最佳方法

如何以编程方式触发`valueChanges`?

在 2 个模块之间共享组件

如何导航到同级路由?

Firebase 查询子项的子项是否包含值

为什么 Angular 项目中没有 Angular-CLI 为 model生成命令?