[英]Event emitter in router-outlet for getting value from child to parent
I have my parent component looks like this我的父组件看起来像这样
<div class='placeholder'>
<router-outlet (newItemEvent)="changeLoadText($event)"></router-outlet>
</div>
I am trying to get some value from child component.我试图从子组件中获取一些价值。
So in the child component Ts file I have created below function to handle the emitted event.所以在子组件 Ts 文件中,我创建了下面的函数来处理发出的事件。
changeLoadText(newLoadingText:string) {
this.loadingText=newLoadingText;
}
@Output() newItemEvent = new EventEmitter<string>();
changeLoadText(value:string){
this.newItemEvent.emit(value);
}
So I am calling the above changeLoadText in few functions in the child component to update spinner text in parent.所以我在子组件的几个函数中调用上面的 changeLoadText 来更新父组件中的微调文本。
So in parent ts file I have created below method to handle emitted event from child所以在父 ts 文件中,我创建了下面的方法来处理从孩子发出的事件
changeLoadText(newLoadingText:string) {
this.loadingText=newLoadingText;
}
But it shows a compile error但它显示一个编译错误
Error: src/app/pages/dashboard/dashboard.component.html:13:51 - error TS2345: Argument of type 'Event' is not assignable to parameter of type 'string'.
13 <router-outlet (newItemEvent)="changeLoadText($event)"></router-outlet>
I didnt understand what I did wrong.我不明白我做错了什么。 Is it because router-outlet is not that something to handle emitted event from child??
是不是因为路由器插座不是用来处理孩子发出的事件的东西??
The router outlet has two events activate
and deactivate
that emit your component ref.路由器插座有两个事件
activate
和deactivate
,它们发出您的组件参考。
Angular documentation - Router Outlet Angular 文档 - 路由器插座
Stackblitz - Router basic example dvsmnx Stackblitz - 路由器基本示例 dvsmnx
So, In your case, If you have loadingText
property in your child component因此,在您的情况下,如果您的子组件中有
loadingText
属性
Child TS儿童 TS
loadingText:string = 'some text';
And your parent component is catching the activate
event with changeLoadText
function并且您的父组件正在使用
changeLoadText
函数捕获activate
事件
Parent HTML父 HTML
<div class='placeholder'>
<router-outlet (activate)="changeLoadText($event)"></router-outlet>
</div>
Then you can have your data using the component reference然后你可以使用组件引用来获取数据
Parent TS父母 TS
changeLoadText(CompRef:any) {
let ChildText:string = CompRef?.loadingText;
console.log(ChildText); // 'some text'
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.