【Angular】组件之间通讯 Input & Output
2018-04-02 10:31
423 查看
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") ;
}
父组件:
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") ;
}
相关文章推荐
- Angular 组件之间数据的传递 之 @Input @Output
- [Angular 2] @Input & @Output Event with ref
- Angular directive父子组件之间通讯
- Angular2父子组件之间数据传递:@Input和@Output (上)
- Angular2父子组件之间数据传递:@Input和@Output (下)
- Angular4-父子组件传值@input@output
- 【angular】组件:@Input() @Output() 输入属性和输出属性以及中间人模式的使用 (一)
- stand IO input & output
- Angular10 组件之间的通讯
- IO(Input&Output)流の介绍
- C++——流的文件I/O(Input & Output)
- 【angular】组件:@Input() @Output() 输入属性和输出属性以及中间人模式的使用 (一)
- angular2之组件通讯
- Angular组件之间的交互
- vue.js组件之间通讯--父组件调用子组件的一些方法,子组件暴露一些方法,让父组件调用
- 一文详尽 Android 通信:四大组件之间 & 进程间 & 线程间 & 多个App间
- 【angular】组件:@Input() @Output() 输入属性和输出属性以及中间人模式的使用 (一)
- input & output in Java demo
- input type = "range"滑块和output的使用