[英]Passing Data From Child Component Into Parent Component
I have problems with my angular, here I have two components: 我的角度有问题,这里有两个组成部分:
I have a property UserNow
in parts MyApp
and I want to set the value of the property UserNow
through the components LoginPage
. 我在部分
MyApp
有一个属性UserNow
,我想通过组件LoginPage
设置属性UserNow
的值。 How to do it? 怎么做?
I have tried (but did not give any influence) 我试过了 (但没有给任何影响)
Import {MyApp} from '../../app/app.component';
@Component({
selector: 'page-login',
templateUrl: 'login.html'
})
export class LoginPage {
public app: any;
login() {
...
this.app = MyApp;
this.app.userNow = MyValue;
...
}
}
There are several ways to do it. 有几种方法可以做到这一点。
1) Using a service: A service generally has a single instance in the application and can be used to share data between the components easily. 1)使用服务:服务通常在应用程序中具有单个实例,并且可以用于容易地在组件之间共享数据。 Eg create a service userService and inject it in components where ever you want to use it.
例如,创建一个服务userService并将其注入您想要使用它的组件中。
2) using Emit: Emit is used to emit an event in the application and corresponding action can be taken. 2)使用Emit:Emit用于在应用程序中发出事件并可以采取相应的操作。
this.eventInChild.emit(data);
Two actions can be taken on event emission. 可以对事件发射采取两种行动。
<child-component (eventInChild)="parentFunction($event)"></child-component>
In Service It goes like this: 在服务中它是这样的:
getEmitStatus() {
return this.eventInService;
}
//In component or service - to listen to event
this.subscription = this.userService.getEmitStatus()
.subscribe(item => {
//thing to do here
});
Like @SaUrAbHMaUrYa explained, you can emit data from child to parent, I would do something like this : 像@SaUrAbHMaUrYa解释的那样,你可以从子节点向父节点发送数据,我会这样做:
Parent 亲
<page-login (on_user_has_logged_in)="userNow = $event"></page-login>
Child : 孩子:
import {Output} from '@angular/core'
import {EventEmitter} from '@angular/core'
@Component({
selector: 'page-login',
templateUrl: 'login.html'
})
export class LoginPage {
@Output() on_user_has_logged_in : EventEmitter<any> = new EventEmitter()
login(MyValue) {
this.on_user_has_logged_in.emit(MyValue)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.