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?
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.
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.
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 {
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With