11

Suppose I have three components: C1, C2, and C3.

I want to make C2 the child of both C1 and C3. And according to the fact which component is the parent of C2 want to show HTML text - "C1 is my parent" or "c3 is my parent". This is the superficial form of my problem. I want to access the name of the parent component in c2, then will change its innerHTML accordingly.

How to access the name of the parent component in angular2?

Ashutosh Sharma
  • 118
  • 2
  • 18

1 Answers1

6

You can simply pass something that will describe your parent component to a child by @Input.

Example of child component:

@Component({
  selector: 'child',
  template: `
    <div>{{ parentName }} is my parent</div>
  `,
})
export class ChildComponent {
  @Input() parentName: string;
}

First parent:

@Component({
  selector: 'first-parent',
  template: `
    <child-component parentName="'first-parent-component'" />
  `,
})
export class FirstParentComponent {
}

Second parent:

@Component({
  selector: 'second-parent',
  template: `
    <child-component parentName="'second-parent-component'" />
  `,
})
export class SecondParentComponent {
}
Patryk Gułaś
  • 847
  • 1
  • 7
  • 19
  • 2
    Yeah, I am using it but I thought there must be some other particular way to do the job, with which we can fetch the name of the parent component directly. – Ashutosh Sharma May 21 '18 at 20:17