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
    }

猜你喜欢

转载自www.cnblogs.com/monkey-K/p/11587382.html