一、父组件给子组件传值-@input
父组件不仅可以给子组件传递简单的数据,还可以将自己的方法以及整个父组件传给子组件
1.父组件调用子组件的时候传入数据
<app-header [msg]="msg"></app-header>
2.子组件引入Input模块
Import{Component,OnInit,Input} from '@anjular/core';
3.子组件中@Input接受父组件出过来的数据
export class HeaderComponent implements OnInit{
@Input() msg:string
constructor() { }
ngOnInit() {
}
}
4.子组件中使用父组件的数据
<h2>这里是头部组件{{msg}}</h2>
二、子组件@Output触发父组件的方法
1.子组件引入Output和Eventemitter
import { Component, OnInit ,Input,Output,EventEmitter} from '@angular/core';
2.子组件中实例化EventEmitter
@Output() private outer=new EventEmitter<stirng>();
3.子组件通过EventEmitter对象outer实例广播数据
sendParent(){
this.outer.emit('msg from child')
}
4.父组件调用子组件时,定义接受事件,outer就是子组件的EventEmitter对象
<app-header (outer)="runParent($event)"></app-header>
5.父组件接收到数据会调用自己的runParent方法,并拿到子组件的数据
runParent(msg:string){
alert(msg);
}
三、父组件通过@ViewChild主动获取子组件的数据和方法
1.调用子组件给子组件定义一个名称
<app-footer #footerChild></app-footer>
2.引入ViewChild
import { Component, OnInit ,ViewChild} from '@angular/core';
3.ViewChild和子组件关联
@ViewChild('footerChild') footer
4.调用子组件
run(){
this.footer.footerRun();
}