After reading this section about component interaction — I've noticed that there is another way of communicating from child to parent ( which wasn't really documented there) :
It turns out that if I have a parent class :
@Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
<my-item></my-item>
</div>
`,
})
export class App {
name:string;
go1()
{
alert(2)
}
constructor() {}
}
And in the child component - I Inject a parent
type into the ctor :
@Component({
selector: 'my-item',
template: `
<div>
<input type="button" value='invoke parent method' (click) = "myGo()"/>
</div>
`,
})
class MyItem {
name:string;
private parent1 : App;
myGo()
{
this.parent1.go1() //<--- access is available here
}
constructor(private parent1 : App)
{
this.parent1 = parent1; //<------------ manually, unlike service
this.name = `Angular! v${VERSION.full}`
}
}
Then Angular sees that i'm trying to inject a parent type class and it gives me access to it.
The click works of course.
Question:
Beside other alternatives which I already know , is it documented anywhere ? or is it just a feature that I can't rely on it
plnkr
This works well and can be used.
A major downside is, that it breaks encapsulation. The child component needs to know about the parent component. This approach makes the child tightly coupled to it's parent, which is usually considered a bad thing because it prevents the component to be re-used anywhere within your application, because it now only works as a child of this exact parent.
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