Reputation: 79
I have a problem with my angular 4 project. In fact I want to send a variable to my parent component. My main component have a variable user :
export class AppComponent {
public user: User = null;
}
His HTML is :
{{user.name}}
<router-outlet></router-outlet>
Instead of router-outlet I have a children component that changes the value of user when I call login():
export class ChildrenComponent {
login() {
user.name = 'Toto';
}
}
Now I would like to sent the value of user to parent component.
Upvotes: 0
Views: 2051
Reputation: 79
Thank you Meir your solution is good ! For the others it's a good solution but with router-outlet I can't use EventEmitter to send my variable
Upvotes: 0
Reputation: 5748
You need to use EventEmmiter for emitting your parent component that user changed and you can send your data in your event for example.
Your parent component template:
<your-child-component (selectedUser)="selectUser($event)"></your-child-component>
Your ParentComponent
:
export class ParentComponent {
user: any;
selectUser(user) {
this.user= user;
}
}
Your ChildComponent
:
export class ChildComponent{
user: any;
@Output() selectUser = new EventEmitter<any>();
onSelectUser(user: any) {
this.selectUser.emit(user);
}
}
You can find good example there
Upvotes: 1
Reputation: 14395
You can use angular's dependency injection.
@Component() {
....
}
export class Parent {
public user: User;
....
}
@Component() {
....
}
export class Child {
constructor(public parent: Parent) {
}
someAction() {
this.parent.user = user;
}
}
Parent and Child are symbolic names, you should substitute to your components names (for example, MainContainer and LoginComponent). Also, you might want to consider making the parent optional so your component will not fail if you use it somewhere else.
Note that this works in normal nesting, you have to check it works with outlets.
You might also want to consider making the parent member an input so it will trigger rendering on value change.
Upvotes: 3