微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

angular 父子组件通信

1.   子组件调用父组件的方法和数据 -- Input 装饰器

 

1. fatherComponent.html中

  tochildStr -- 父组件中定义的数据

  fatherMethod -- 父组件中的方法

  fatherComponent -- 父组件本身, this指代父组件实例,通过 [fatherCompoent] 将父组件实例传递给子组件

<childComponent #login [tochildStr]="tochildStr" [fatherMethod]="fatherMethod" [fatherComponent]="this"></app-login>

2. childComponent.ts 中

  

  通过 @Input 装饰器获取父组件属性方法,父组件实例

export class LoginComponent implements OnInit {   @input() tochildStr: string -- 父组件属性   @input() fatherMethod:any -- 父组件方法   @input() fatherComponent: any -- 父组件实例   constructor() { }   ngOnInit() {   }   getFatherComponentMethod() {     alert(this.tochildStr) -- -- 父组件属性     alert(this.fatherComponent.tochildStr) -- -- 父组件实例获取父组件属性     this.fatherComponent.fatherMethod() -- -- 父组件实例调用父组件方法     this.fatherMethod() -- -- 父组件方法   } }

 

2.   父组件调动子组件的方法和数据 -- ViewChild装饰器

  

  1. fatherComponent.html中

  通过#var 方式给子组件标记

<childComponent #child></childComponent>

  2. fatherComponent.ts中

  通过@ViewChild()装饰器获取子组件实例

 @ViewChild('child', null) childComponent: any   userChildMethod() {     // 调用子组件方法 -- 获取属性同样写法     this.childComponent.childMethod()   }

3. 通过事件触发器,子组件给父组件传参。即父组件获取子组件数据

以上两种方式都是主动获取数据或者方法。这种方式通过 EventEmitter 和 outPut 方式相当于,通过事件,子组件广播数据给父组件,父组件被动接受参数。

  1. childComponent.ts

  

import { Output, EventEmitter } from '@angular/core'; export class LoginComponent implements OnInit {   @Output() outer:any = new EventEmitter() -- 声明并且输出一个事件触发器   public msg = "123"   public obj = {     num: 1   }   sendParent() {     this.outer.emit(this.obj) -- 通过事件触发器,发送数据给父组件   }

  2. childComponent.html

  

  <h5>通过事件触发器,子组件向父组件广播数据</h5>   <button (click)="sendParent()">数据发送给父组件</button>

  3. parentComponent.html,

通过 (事件触发器)= “方法” 的方式监听子组件发出父消息。 (事件触发器) 必须与子组件中定义的名称一致

  

  <childComponent (outer)="onReciveChildMsg($event)"></childComponent>

  

  4. parentComponent.ts

  通过方法获取传递的参数 $event

  onReciveChildMsg(e) {       alert(e.num)       e.num = 2       // e = "456"       // this.msg = e     }

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐