- 父组件传给子组件, 可以传data, function, self自身
//父组件
<app-header [title]="title" [msg]="msg" [run]="run" [home]="this">
</app-header>
<div>
<p>home</p>
</div>
//子组件
/*
* @Author : G.F
* @Date : 2020-05-13 20:45:05
* @LastEditTime : 2020-05-16 23:24:56
* @LastEditors : G.F
* @FilePath : /angularproject/src/app/components/header/header.component.ts
* @Description :
*/
import { Component, OnInit, Input } from '@angular/core';
export class HeaderComponent implements OnInit {
//接收父组件传来的数据
@Input() title:any;
@Input() msg:any;
// 传入function
@Input() run:any;
// 传入父组件自身,this 绑定的
@Input() home:any;
constructor() { }
ngOnInit(): void {
}
getParentMsg(){
// alert(this.msg)
alert(this.home.msg)
}
getParentRun(){
// this.run()
this.home.run()
}
}
2. 父组件接收子组件data and function
1 ViewChild 方法
//父组件
<app-header [title]="title" [msg]="msg" [run]="run" [home]="this" #headerChild>
</app-header>
<div>
<p>home</p>
<button (click)="getChild()">父组件获取子组件的data</button>
<button (click)="getChildFun()">父组件获取子组件的function</button>
</div>
/*
* @Author : G.F
* @Date : 2020-05-13 20:30:38
* @LastEditTime : 2020-05-17 10:52:30
* @LastEditors : G.F
* @FilePath : /angularproject/src/app/components/home/home.component.ts
* @Description :
*/
import { Component, OnInit, ViewChild } from '@angular/core';
import { log } from 'util';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
@ViewChild('headerChild') headerChild:any;
constructor() { }
ngOnInit(): void {
}
getChild(){
console.log(this.headerChild.message)
}
getChildFun(){
this.headerChild.messageFun()
}
}
2 @Output 和 EventEmitter获取
//子组件
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
//子组件引入装饰器
@Output() private outer = new EventEmitter();
//定义@Output的装饰器
emitData() {
this.outer.emit('子组件的data');
}
//子组件emit给父级的方法, 点击触发
<button (click)="emitData()">提交数据给父级</button>
//父组件里的子组件
<app-header (outer)="getChildMsg($event)"></app-header>
//父级通过outer事件接受,参数是$event, outer必须和子组件定义的变量名一致
getChildMsg(msg) {
console.log(msg, '子组件data');
}