父子组件通讯

组件传值 事件绑定

输入 Input属性通常接收数据值。 输出 Output属性暴露事件生产者,如 EventEmitter 对象。

//父组件
<app-test-details [hero]="hero" (setHero)="setHeroName($event)"></app-test-details>
//接收子组件事件
setHeroName(hero: Hero) {
    this.heros.forEach(val => {
      if (val.id === hero.id) {
        val.name = hero.name;
      }
    });
}
//子组件
import {Component, OnInit, Input, Output, EventEmitter} from '@angular/core';
export class TestDetailsComponent implements OnInit {
  //接收父组件数据
  @Input() hero: Hero;
  //@Input('newHero') hero: Hero;  //起别名  (不推荐起别名)
  //输出方法
  @Output() setHero = new EventEmitter();
  updateHero() {
     //将数据传递给父组件   调用父组件事件
     this.setHero.emit(this.hero);
  }
}

父组件调用子组件事件

1.父组件与子组件通过本地变量互动

#hero

<app-test-details #child [hero]="hero"></app-test-details>
<button (click)="child .testParent()">click</button>

//子组件中定义方法
testParent() {
   console.log("子组件方法被调用")
}
2.父组件通过@ViewChild()调用子组件事件

@ViewChild()

import {Component, OnInit, ViewChild} from '@angular/core';
import {TestDetailsComponent} from '../test-details/test-details.component';
export class TestComponent implements OnInit {
  @ViewChild(TestDetailsComponent)
  child: TestDetailsComponent;
  constructor() {}
  clickTest() {
   //调用子组件事件
    this.child.testParent();
  }
}
3.父组件和子组件通过服务来通讯
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一. 单输入型属性传递与监听 通常父子组件传递信息的方法: 子组件通常含有输入型属性:通常带有@input()装饰...
    柳源居士阅读 2,515评论 0 0
  • Vue父子组件通讯传值 父组件往子组件传值 子组件与父组件通信 方式1 采用中间件作为通讯中转站实现子组件往父级组...
    进击的切图仔阅读 1,664评论 0 0
  • 父子组件通讯总结为 “ prop 向下传递,emit事件向上传递”。 父组件通过 prop 给子组件下发数据,子组...
    阿木心阅读 903评论 0 0
  • 组件间交互简单来说就是让两个或多个组件之间共享信息。接下来我们就对Angular2组件间的交互做一个简单的解...
    tuacy阅读 4,944评论 0 2
  • 一、父组件 二、子组件 三、父组件通过props向子组件传递参数,子组件通过调用父组件的回调函数callback并...
    胡_松阅读 2,726评论 0 0