If the parent components are not connected hierarchically or are siblings, a simple and type-safe approach is to create an enum
for the parent types:
export enum ParentType {
TypeA = 'Parent A',
TypeB = 'Parent B'
}
You can then define an @Input
property in your ChildComponent
, like so:
import { Component, Input } from '@angular/core';
import { ParentType } from './parent-type.enum';
@Component({
selector: 'child',
template: `<h1>My Parent IS {{ parent }}</h1>`,
styles: [`h1 { font-family: Lato; }`]
})
export class ChildComponent {
@Input() parent: ParentType;
}
And use it in your parent components as follows:
For Parent Component 1:
import { Component, Input } from '@angular/core';
import { ParentType } from './parent-type.enum';
@Component({
selector: 'parent-a',
template: `<child [parent]="parent"></child>`,
styles: [`h1 { font-family: Lato; }`]
})
export class ParentAComponent {
parent = ParentType.TypeA;
}
For Parent Component 2:
import { Component, Input } from '@angular/core';
import { ParentType } from './parent-type.enum';
@Component({
selector: 'parent-b',
template: `<child [parent]="parent"></child>`,
styles: [`h1 { font-family: Lato; }`]
})
export class ParentBComponent {
parent = ParentType.TypeB;
}
Check out this Sample StackBlitz for reference.