Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

angular2 组件通讯 #43

Open
pengkobe opened this issue Apr 30, 2017 · 1 comment
Open

angular2 组件通讯 #43

pengkobe opened this issue Apr 30, 2017 · 1 comment

Comments

@pengkobe
Copy link
Owner

pengkobe commented Apr 30, 2017

这算是 Angularjs1.x 与 Angular2 一个重大的区别了,切换到 Angular2 编程还真有点适应不过来,不过用起来发现,Angular2 的通讯方式语义更清楚,协作起来更方便。

通讯方式

父->子 input 方式(已淘汰)

这种方跟 Angularjs1.x 的方式私以为无差异

  1. 父组件引入指令directives: [Child]
  2. 在模板中绑定变量[content]="i"
  3. 在子组件中即可以直接使用了{{content}}

子->父 output 方式

这种方式基于事件

  1. 在子组件中声明事件发布器@Output() updateNumberI:EventEmitter<number> = new EventEmitter();
  2. 在模板中绑定事件处理函数(updateNumberI)="numberIChange($event)"
  3. 发布,this.updateNumberI.emit(++this.i);

父获得子实例

  1. 声明子组件实例 @ViewChild(Child) child:Child;
  2. 直接调用子组件的方法

service 方式

  1. 声明 service
  2. 父组件操作 service 更改数据,子组件直接引用 service 中的数据{{service.i}}

service EventEmitter方式

这种方式在 Angular1.x 中用的也比较多,只不过那时候用的是 $rootscope 上的方法。

  1. 增加 service 作为事件代理器
  2. 父组件发布事件
  3. 子组件接收事件

参考

kittencup/angular2-ama-cn#23

@pengkobe
Copy link
Owner Author

话说哪几种方式比较好呢,或者适应的场景是什么?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant