父传子
1.父组件引用子组件,并绑定需要传的值或者方法
<!-- 父组件调用子组件 -->
<app-son [id]="id" [run]="run"></app-son>
2.子组件接收
import { Component, OnInit, Input } from '@angular/core';
@Input() id:any; // 接收值
@Input() run:any; // 接收方法
this.run(); //可直接使用方法
doSubmit(){
console.log(this.id); // 也可直接使用值
}
子传父
1.父组件引用子组件
<!-- 父组件调用子组件 -->
<app-son #son (outer)="run($event)"></app-son>
<!-- 定义获取子组件信息的方法 -->
<button (click)="getChildMsg()">获取子msg</button>
<button (click)="getChildFunc()">获取子方法</button>
2.父组件在ts中获取子组件的实例
import { Component, OnInit, Input, ViewChild } from '@angular/core';
//根据ViewChild获取子组件实例
@ViewChild('son') son:any;
//调用方法,可获取子组件的数据及方法
getChildMsg(){
console.log(this.son.msg);
}
getChildFunc(){
this.son.run();
}
3.子组件通过广播的形式,向父组件发送数据
//子组件引用Output, EventEmitter
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
//获取引用实例
@Output() private outer = new EventEmitter();
//定义方法向父组件传值
setParent(){
//向父组件传值
this.outer.emit("我是子组件的数据")
}
4.父组件接收
在html中绑定了(outer)="run($event)"后,在父组件的ts文件中:
// 子组件广播时触发父组件方法,
run(event:any){
console.log(event);
}