vivek
vivek

Reputation: 87

Unable to pass value from parent to child component in angular 9

Basically scenario is, i am shifting the value of variable up to its grand-parent component using EventEmitter (till now its working fine).

but once value reaches at grand-parent i want to pass that value to its another child component. i am doing it with @input name:string at child component. but don't know why i am not able to get that name in that child component.

parent =>

//html code
<personal-section (childName)="getName($event)"></personal-section>
<profile-section [name]="name"></name>

//inside profile.ts
 getName($event) {
    console.log(this.name);       // <--- upto this console, program works fine
    this.name= $event;
  }

child =>

 @Input() name: any;
 ngOnChanges() {
    if (this.name) {
      console.log('users name is ', this.name);    //<--this never prints.
    }
  }

but whenever i perform click event in grand-child's component, value perfectly reaches upto its grand-parent. but after that i am not able to get it in its another child i.e final destination ;)

Thanks in advance.

Upvotes: 0

Views: 1265

Answers (1)

Barremian
Barremian

Reputation: 31125

Replacing the getName($event) in the controller with getName(event) is only a matter of convention.

Besides, if you only want to send the name variable from one child to another child, you could do it without involving the parent using custom variable. Try the following

Parent template

<personal-section (childName)="profileSection1.setName($event)"></personal-section>
<profile-section #profileSection1></name>

The @Input decorator can then be removed from the name property in 'profile section' component.

Profile section component

export class ProfileSectionComponent implements OnInit {
  name: any;

  public setName(name: any) {
    this.name = name;
    console.log('User name is ', this.name);
  }
  .
  .
}

Upvotes: 1

Related Questions