Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular — an undocumented child-to-parent communication?

Tags:

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

like image 491
Royi Namir Avatar asked Apr 16 '17 09:04

Royi Namir


1 Answers

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.

like image 124
Günter Zöchbauer Avatar answered Oct 11 '22 22:10

Günter Zöchbauer