gpt4 book ai didi

Angular2 EventEmitter 触发父组件

转载 作者:太空狗 更新时间:2023-10-29 17:33:49 25 4
gpt4 key购买 nike

我正在尝试从子组件向父组件触发一个事件。

 @Component({
template:'<foo></foo>'
})
export class ParentComponent{
onDoSomething($event){
//do work here
}

}

@Component({
selector:'foo'
template:<button (click)="onClick($event)">MyButton</button>
})
export class ChildComponent{
myEvent eventName = new EventEmitter();

onClick(button){
this.eventName.emit(button);
}

}

我如何让它工作?

最佳答案

您使用 @Output 在您的子组件中定义一个 EventEmitter

@Component({
selector:'foo',
template:`<button (click)="onClick($event)">MyButton</button>`
})
export class ChildComponent{
@Output() myEvent = new EventEmitter();

onClick(button){
this.myEvent.emit(button);
}

}

然后你像这样在你的父组件中“订阅”这个事件:

@Component({
selector: 'my-app',
template: `Hello World <foo (myEvent)="myEvent($event)"></foo>`,
directives: [],
providers: []
})
export class AppComponent {

myEvent($event){
console.log(1, $event);
}
}

完整示例:http://plnkr.co/edit/MeQbC7Jbc8rprMF66aEF?p=preview

关于Angular2 EventEmitter 触发父组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40940302/

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