Reputation: 128
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?
Upvotes: 12
Views: 4638
Reputation: 21
You could use the the ActivatedRoute
. where you can use the activatedRoute.snapshot.component
And then if you want it in an if statement for type comparison =>
if(this.activatedRoute.snapshot.component === YourComponentParentName)
Do stuff....
Upvotes: 0
Reputation: 997
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 {
}
Upvotes: 7