【发布时间】:2016-10-18 13:28:58
【问题描述】:
好的,这就是我想要实现的目标:
我有这个组件:
import { Component, Output, EventEmitter, OnInit } from '@angular/core';
@Component({
selector: 'like',
template: '<p>this is the like component<p>'
})
export class LikeComponent implements OnInit{
title: string = 'Like Component';
@Output() sendTitle = new EventEmitter();
ngOnInit() {
this.sendTitle.emit({title: this.title});
}
}
我想将标题从它发送给父母:
import { Component, Input } from '@angular/core';
@Component({
moduleId: module.id,
selector: 'panel',
template: `
<div class="panel panel-default">
<div class="panel-heading">
<h2 class="panel-title">{{title}}</h2>
</div>
<div class="panel-body">
<ng-content (sendTitle) = "receiveTitle($event)"></ng-content>
</div>
</div>
`
})
export class PanelComponent {
title = 'default title';
receiveTitle(arg) {
this.title = arg.title;
console.log(arg);
}
}
然后我可以将PanelComponent 与我想包装在面板中的每个组件一起重用:
<panel>
<like></like>
</panel>
<panel>
<another-component></another-component>
</panel>
<panel>
<exemple-component></exemple-component>
</panel>
每次显示Panel 组件时,它都会尝试从事件中获取标题(如果存在)。
这似乎不适用于 ng-content,因为它与常规父/子组件一样?我对 angular 2 不熟悉,因此非常感谢您的反馈!
tl;dr :我想让父母知道孩子的属性,但孩子不能具体(这就是我使用<ng-content> 的原因)。
简而言之,我不想像这样通过input 这样做:
<panel [title] = "'This is the panel title of the like component'">
<like></like>
</panel>
<panel [title] = "'This is the panel title of the another-component'">
<another-component></another-component>
</panel>
【问题讨论】:
标签: angular typescript components parent-child