父传子 @input
父组件不仅可以给子组件传递简单的数据,还可以把自己的方法以及整个父组件传给子组件
子组件获取父组件的 msg 数据
- 父组件调用子组件的时候传入数据
<app-son [msg]="msg"></app-son>
- 子组件引入 Input 模块
import { Input } from '@angular/core'
- 子组件中 @Input 接收父组件传过来的数据
export class SonComponent implements OnInit {
@Input() msg: string
ngOnInit () {
console.log(this.msg)
}
}
子组件调用父组件的 run 方法
- 父组件调用子组件的时候传入方法
<app-son [run]="run"></app-son>
- 子组件引入 Input 模块
import { Input } from '@angular/core'
- 子组件中 @Input 接收父组件传过来的方法
export class SonComponent implements OnInit {
@Input() run: any
ngOnInit () {
this.run()
}
}
子组件获取调用父组件所有的数据或方法
- 父组件调用子组件的时候传入 this (接收参数 all 是任意的)
<app-son [all]="this"></app-son>
- 子组件引入 Input 模块
import { Input } from '@angular/core'
- 子组件中 @Input 接收父组件传过来的数据/方法
export class SonComponent implements OnInit {
@Input() all: any
ngOnInit () {
console.log(this.all.msg)
this.all.run()
}
}
子传父
父组件获取调用子组件所有的数据或方法(ViewChild)
- 给子组件 DOM 节点起个名字
<app-son #son></app-son>
- 父组件引入 ViewChild 模块
import { ViewChild } from '@angular/core'
- 通过 @ViewChild 获取子组件数据/方法
@ViewChild('son') son: any
ngAfterViewInit (): void {
console.log(this.son.data)
this.son.func()
}
子组件通过 @OutPut 触发父组件的方法
- 子组件引入 Output 和 EventEmitter
import { Output, EventEmitter } from '@angular/core'
- 子组件中实例化 EventEmitter
// 用 EventEmitter 和 output 装饰器配合使用 <string> 指定类型的变量
@Output() private outer = new EventEmitter<string>()
- 子组件通过 EventEmitter 对象 outer 实例化广播数据
ngOnInit () {
this.sendParent()
}
sendParent () {
this.outer.emit('i am son-component')
}
- 父组件调用子组件的时候,定义接收事件,outer 就是子组件的 EventEmitter 对象 outer
<app-son (outer)="runParent($event)"></app-son>
- 父组件接收到数据会调用自己的 runParent 方法,这个时候就能拿到子组件的数据
runParent (val) {
console.log(val) // i am son-component
}