(二)Angular 2 组件通信(ViewChild,EventEmitter)

一、ViewChild 方法(不便于组件解耦及组件重用)

1.创建父组件parent

2.创建子组件child

3.在child中创建 print 方法

print() {
    alert('print);
}

4.在parent.component.html中引入child组件

<app-child #child></app-child>

5.在parent中引入ViewChild并执行child方法

@ViewChild('child')
child: ChildComponent; //父组件中获得子组件的引用

ngOnInit(){
  this.child.print();
}

二、EventEmitter 方法,实质是使用Angular所提供的输入输出(Input,Output)(便于组件解耦,组件重用)

1.创建父组件parent

2.创建子组件child

3.在child中创建 print 方法

print() {
    alert('print);
}

4.在parent中定义EventEmitter 事件,并抛出

public parentEvt: EventEmitter<any> = new EventEmitter();

public emitEvt() {
    this.parentEvt.emit();   
}

5.在parent.component.html中引入child组件并传入parent的Event事件

<app-child [evt]='parentEvt'></app-child>

6.在child中使用@Input接收Event事件(参考Angular@Input用法),同时增加取消订阅事件(ngDestroy)

private pEvtSub: Subscription = null;
private pEvt: EventEmitter<any> = null;

@Input()
public set evt(value: EventEmitter<any>) {
    this.pEvt = value;
    if (!this.pEvt) {
        return
    }
    if (this.pEvtSub) {
        this.pEvtSub.unsubscribe();
    }
    this.pEvtSub = this.pEvt.subscribe((evt) => {
        this.print()
    });
}

ngDestroy() {
  if (this.pEvtSub) {
    this.pEvtSub.unsubscribe();
  }
}

三、EventEmitter + Service 方法,实质是建立一个EventService做为中转进行事件发布,组件在ngOnInit中对事件进行订阅

转载于:https://www.cnblogs.com/chendongbky/p/11212094.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值