Angular - undocumented communication with parent child?

After reading this section on component interactions - I noticed that there is another way to communicate from child to parent (which wasn’t really documented):

It turns out 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 Enter a parent in 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}` } } 

Angular then sees that I'm trying to introduce a class of the parent type, and it gives me access to it.

The click works, of course.

Question:

Along with other alternatives that I already know, is it documented somewhere? or is it just a function that I cannot rely on.

plnkr

+5
source share
1 answer

It works well and can be used.

The main disadvantage is that it destroys encapsulation. The child component must know about the parent component. This approach makes the child closely connected with his parent, which is usually considered bad, since he prevents the reuse of the component anywhere in the application, since now he works only as a child of this exact parent.

+3
source

Source: https://habr.com/ru/post/1266784/


All Articles