0

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.

3
  • 2
    Visit: angular.io/guide/… Commented Oct 12, 2017 at 12:37
  • Event Emitters, services, a few different ways to do this: angular.io/guide/… Commented Oct 12, 2017 at 12:39
  • Event emitter might not work when dealing with router outlets, you have now way of making the specific binding. Commented Oct 12, 2017 at 12:43

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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

1 Comment

Btw, the service solution is probably a good way as well. The parent/child works but it is good for things such as tabs, when it comes to user, an application wide value, a service sounds better

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.