假设我有一个 angular 的祖父类,它的 html 如下所示:
<parent>
<child></child>
</parent>
父级有一个子级需要呈现的变量,它由父级传递给子级,子级将其绑定到自己的预定义 html 中。我怎样才能做到这一点?ViewChild 和 ContentChild 似乎都没有完全工作。
假设父组件和子组件如下所示:
@Component({
selector: 'parent',
template: `
<div>
My name is {{name}} <br>
children:
<ng-content></ng-content>
</div>
`,
styleUrls: ['./parent.component.css']
})
export class ParentComponent {
name = 'Donald Duck';
}
@Component({
selector: 'child',
template: `
<div>
My parent is called {{parentName}}
</div>
`,
styleUrls: ['./child.component.css']
})
export class ChildComponent {
@Input() parentName: string;
}
然后您可以使用模板变量引用父级:
<parent #parent>
<child [parentName]="parent.name"></child>
</parent>
演示:https : //stackblitz.com/edit/angular-moa7n8
编辑:回答评论中的问题:
这非常接近,但是有没有一种方法可以让我在父级或子级中完成该任务并使祖父级尽可能简单?
是的,您可以实现使用ContentChild
和AfterContentInit
生命周期挂钩。
export class ParentComponent implements AfterContentInit {
@ContentChild(ChildComponent) child: ChildComponent;
name = 'Donald Duck';
ngAfterContentInit() {
this.child.parentName = this.name;
}
}
然后祖父母模板将非常简单:
<parent>
<child></child>
</parent>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句