您的位置:首页 > 编程语言 > PHP开发

【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") ;
  }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: