我有两个这样的组件:
@Component({
selector: 'comp1',
template: `<h1>{{ custom_text }}</h2>`
})
export class Comp1 {
custom_text:string;
constructor(text:string) {
this.custom_text = text;
}
}
/*********************************************/
@Component({
selector: 'comp2',
directives: [Comp1],
template: `
<b>Comp 2</b>
<comp1></comp1>
`
})
export class Comp2 {
constructor() {
// ...
// How to send my own text to comp1 from comp2
// ...
}
}
是否可以将我自己的文本从
comp1
发送到 comp2
?
是否可以从
comp1
获取 comp2
实例?
comp2 是 comp1 的父级,所以
@Output() someEvent = newEventEmitter();
emit()
其上的事件:this.someEvent.emit('some text');
<comp2 (someEvent)="someHandler()"></comp2>
@ViewChild
或 @Query
: @ViewChild(Comp1) viewChild:comp1;
然后,您可以在 this.comp1
中访问 ngAfterViewInit()
,或在组件生命周期的后期。是的,这很容易实现,
查看教程:多个组件 Angular2 教程的第 3 部分了解如何发送输入。
@Component({
selector: 'comp1',
template: `<h1>{{customText}}</h2>`,
inputs: ['customText']
})
export class Comp1 {
public customText:string;
constructor(text:string) {
this.customText= text;
}
// ngOnChange to make sure the component is in sync with inputs changes in parent
ngOnChanges() {
this.customText= text;
}
}
/*********************************************/
@Component({
selector: 'comp2',
directives: [Comp1],
template: `
<b>Comp 2</b>
<comp1 customText = "My Custom Test"></comp1>
`
})
export class Comp2 {
constructor() {
}
}
尝试一下,让我知道效果如何。