6.1 父传子
6.1.1 父组件给子组件传值
1)父组件调用子组件的时候传入数据
<app-header [msg]="msg"></app-header>
2)子组件引入 Input 模块
import { Component, OnInit ,Input } from '@angular/core';
3)子组件中 @Input 接收父组件传过来的数据
export class HeaderComponent implements OnInit {
@Input() msg:string
constructor() { }
ngOnInit() {
}
}
4)子组件中使用父组件的数据
<h2>这是头部组件--{{msg}}</h2>
6.1.2 父组件给子组件传方法
1) 父组件调用子组件时传入方法
<app-header [run]=”run”></app-header>
2) 子组件引入 Input 模块
import { Component, OnInit ,Input } from '@angular/core';
3) 子组件接收父组件传来的方法 @Input run:any;
4) 子组件中使用父组件的方法 this.run()
6.1.3 整个父组件传给子组件
- <app-header [home]=”this”></app-header>
- 调用 this.home.msg
6.2 子传父
6.2.1 子组件通过ViewChild给父组件传值
方法同5.3
6.2.2 子组件通过@Output 给父组件传值
- 子组件引入 Output 和 EventEmitter
import { Component, OnInit ,Input,Output,EventEmitter} from '@angular/core';
- 子组件中实例化 EventEmitter
@Output() private ourter = new EventEmitter()
- 子组件通过 EventEmitter 对象 outer 实例广播数据
this.ourter.emit(this.msg);
- 父组件调用子组件时,定义接收事件outer就是子组件定义的outer
<app-header (outer)=”runParent($event)”></app-header>
- 父组件调用自己的runParent()方法接收子组件传来的数据
runParent(e){ alert(e) }
6.3 非父子组件传值
1) 公共服务的LocalStorage(推荐)
2) 服务 (参照 4 创建服务)
3) Cookie