Input 【 父组件向子组件传入数据 】
父组件:
1. 准备数据(或引入服务中获取数据)
import { Hero } from '../hero'; // 定义类型
import { HEROES } from '../mock-hero'; // json数据
heroes = HEROES;
2. 公共接口(属性绑定)
<app-hero-detail [hero]="selectedHero"></app-hero-detail>
子组件:
1. 引入input获取数据
import { Component, OnInit ,Input } from '@angular/core';
@Input() hero: Hero;
2. 展示数据
<label>
name: <input [(ngModel)]="hero.name">
</label>
注:使用双向绑定[( ngModel )],必须引入form模块
import { FormsModule } from '@angular/forms';
imports: [
FormsModule
],
Output 【 子组件向父组件传出数据 】
父组件:
1. 公共接口
<app-child (outer)="receive($event)"></app-child>
2. 方法
receive(msg: string){
this.msgFromChild = msg;
}
子组件:
1. 引入output
import { Component, OnInit, Input , Output , EventEmitter} from '@angular/core';
2.输出output
@Output() private outer = new EventEmitter<string>();
3. 触发事件
<button (click)="sendToParent()">发送给父组件</button>
sendToParent(){
this.outer.emit("message from child") ;
}