angularparent-childmean-stack

How to get the name of the Parent component in Child component in angular 2?


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?


Solution

  • 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 {
    }