angular——父子组件通信

父传子 @input

父组件不仅可以给子组件传递简单的数据,还可以把自己的方法以及整个父组件传给子组件

子组件获取父组件的 msg 数据
  1. 父组件调用子组件的时候传入数据
<app-son [msg]="msg"></app-son>
  1. 子组件引入 Input 模块
import { Input } from '@angular/core'
  1. 子组件中 @Input 接收父组件传过来的数据
export class SonComponent implements OnInit {
  @Input() msg: string

  ngOnInit () {
    console.log(this.msg)
  }
}
子组件调用父组件的 run 方法
  1. 父组件调用子组件的时候传入方法
<app-son [run]="run"></app-son>
  1. 子组件引入 Input 模块
import { Input } from '@angular/core'
  1. 子组件中 @Input 接收父组件传过来的方法
export class SonComponent implements OnInit {
  @Input() run: any

  ngOnInit () {
    this.run()
  }
}
子组件获取调用父组件所有的数据或方法
  1. 父组件调用子组件的时候传入 this (接收参数 all 是任意的)
<app-son [all]="this"></app-son>
  1. 子组件引入 Input 模块
import { Input } from '@angular/core'
  1. 子组件中 @Input 接收父组件传过来的数据/方法
export class SonComponent implements OnInit {
  @Input() all: any
  
  ngOnInit () {
    console.log(this.all.msg)
    this.all.run()
  }
}

子传父

父组件获取调用子组件所有的数据或方法(ViewChild)
  1. 给子组件 DOM 节点起个名字
  <app-son #son></app-son>
  1. 父组件引入 ViewChild 模块
 import { ViewChild } from '@angular/core'
  1. 通过 @ViewChild 获取子组件数据/方法
  @ViewChild('son') son: any

  ngAfterViewInit (): void {
    console.log(this.son.data)
    this.son.func()
  }
子组件通过 @OutPut 触发父组件的方法
  1. 子组件引入 Output 和 EventEmitter
import { Output, EventEmitter } from '@angular/core'
  1. 子组件中实例化 EventEmitter
  // 用 EventEmitter 和 output 装饰器配合使用 <string> 指定类型的变量
  @Output() private outer = new EventEmitter<string>()
  1. 子组件通过 EventEmitter 对象 outer 实例化广播数据
  ngOnInit () {
    this.sendParent()
  }
  
  sendParent () {
    this.outer.emit('i am son-component')
  }
  1. 父组件调用子组件的时候,定义接收事件,outer 就是子组件的 EventEmitter 对象 outer
<app-son (outer)="runParent($event)"></app-son>
  1. 父组件接收到数据会调用自己的 runParent 方法,这个时候就能拿到子组件的数据
  runParent (val) {
    console.log(val) // i am son-component
  }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值