angular中@input和@output
1.父组件调用子组件的时候传入数据
<app-header [msg]="massage"></app-header>
2.子组件引入input模块
import{Component,OnInit,Input}from'@angular /core';
3.子组件@input接收父组件传过来的数据
export class HeadrComponent implements OnInit {
@Input()msg:string
}
4.子组件使用父组件的数据
<h2>{{msg}}</h2>
二、子组件通过@output触发父组件的方法
1.子组件引入Output和EventEmitter
import { Component, OnInit ,Input,Output,EventEmitter} from '@angular/core';
2.子组件中实例化EventEmitter
@Output() private outer=new EventEmitter<string>();
3.子组件通过EventEmitter对象outer实例广播数据
sendParent(){
this.outer.emit('msg from child')
}
4.父组件调用子组件的时候,定义接收事件,outer就是子组件的EventEmitter对象outer
<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();
}
四、非父子组件通讯
1、公共服务
2、localstorage(推荐)
3、cookie