首页 文章

Angular - 一种无证的儿童与父母之间的沟通?

提问于
浏览
5

读完之后section about component interaction - 我真的记录在那里):

事实证明 if 我有一个父类:

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
      <my-item></my-item>
    </div>
  `,
})
export class App {
  name:string;
  go1()
   {
     alert(2)
   }
  constructor() {}
}

在子组件中 - 我将一个 parent 类型注入到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看到我正在尝试注入一个父类型类,它让我可以访问它 .

点击工作当然 .

Question:

除了我已经知道的其他替代方案,它是否记录在任何地方?或者它只是一个我不能依赖它的功能

plnkr

1 回答

  • 4

    这很好用,可以使用 .

    一个主要的缺点是,它破坏了封装 . 子组件需要知道父组件 . 这种方法使得孩子与父母紧密耦合,这通常被认为是一件坏事,因为它会阻止组件在应用程序中的任何地方重复使用,因为它现在只能作为这个确切父母的孩子 .

相关问题