我有一个 Angular 组件 app-b,它在组件 app-a 中使用,该组件 app-a 在 app-component 中使用。 app-component 在 app-a 中有一些内容,app-a 将此内容与 ng-content 转换为 app-b,app-b 将其与另一个 ng-content 一起显示 - 但我如何在组件中访问此内容(而不是它是模板)?
我认为 ContentChild 是正确的方法,但似乎是错误的。
例子:
https://stackblitz.com/edit/angular-ddldwi
编辑:更新示例
最佳答案
您不能使用 @ContentChild
装饰器按标签名称查询。您可以通过模板变量、组件或指令选择器进行查询。
app-a.component.html
<app-b>
<ng-content></ng-content>
<p #myContent>This is a content child for app-b.</p>
</app-b>
app-b.component.ts
import { Component, AfterContentInit, ContentChild } from '@angular/core';
@Component({
selector: 'app-b',
templateUrl: './b.component.html',
styleUrls: ['./b.component.css']
})
export class BComponent implements AfterContentInit {
@ContentChild('myContent') contentchild;
ngAfterContentInit() {
console.log(this.contentchild);
}
}
关于javascript - 如何访问已经嵌入的 ContentChild?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49904027/