Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 331
Ashutosh Sharma Avatar asked May 21 '18 18:05

Ashutosh Sharma


People also ask

How do you call a child component method in parent component in Angular 2?

When user focus on ParentComponent's input element, you want to call ChildComponent's doSomething() method. Simply do this: Give app-child selector in parent. component.

How do you use the parent component variable in a child component?

If you want to pass data from the parent component to the child component, you need to use two things: @Input and property binding. In this example, we set in the child component a variable named childExample , which is a string. We set Angular's @Input decorator in front of the variable.


1 Answers

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 {
}
like image 107
Patryk Gułaś Avatar answered Oct 21 '22 23:10

Patryk Gułaś