gpt4 book ai didi

typescript - Angular 2 - 获取组件实例

转载 作者:太空狗 更新时间:2023-10-29 18:14:25 24 4
gpt4 key购买 nike

我有两个这样的组件:

@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

是否可以从comp2获取comp1实例?

谢谢。

最佳答案

comp2 是 comp1 的父级,所以

  • 将数据从 child 发送到 parent (comp1 到 comp2)添加 OutputProperty给 child :
    @Output() someEvent = newEventEmitter();
    emit()一个事件:this.someEvent.emit('some text');
    父级需要绑定(bind)到输出属性/事件:<comp2 (someEvent)="someHandler()"></comp2>
  • 要获取对子组件实例的引用(comp2 获取对 comp1 的引用),请使用 @ViewChild @Query 在 comp2 中:@ViewChild(Comp1) viewChild:comp1;然后您可以访问 this.comp1ngAfterViewInit() ,或组件生命周期的后期。

关于typescript - Angular 2 - 获取组件实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35567019/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com