Skip to content

父子组件通信

子组件

child.html

<div>
  <span>父组件传递的数据: {{ parentMsg }}</span>
  <span (click)="click()">点击向父组件传递数据:{{ childMsg }}</span>
</div>

child.ts

import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.scss']
})

export class ChildComponent implements OnInit {

  @Output() change = new EventEmitter<any>();
  
  childMsg = '我是子组件 child';
  parentMsg = '';
  
  ngOnInit() {
    
  }
  
  getData(msg){
    // 接收父组件传递的值【动态传值】
    this.parentMsg = msg;
  }
  
  click(){
    // 向父组件传值
    this.change.emit(this.childMsg);
  }
  
}

父组件

parent.html

<child #child (change)="change($event)"></child>
<div (click)="click()">点我向子组件传值</div>

parent.ts

import { Component, OnInit, ViewChild } from '@angular/core';
import {ChildComponent} from './child.component';

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.scss']
})
export class ParentComponent implements OnInit {

  @ViewChild('child', { static: true}) child:ChildComponent;
  
  parentMsg = '我是父组件 parent';

  constructor() {}

  async ngOnInit() {}

  change(e) {
    // 接收父组件传递的值
    console.log(e);
  }
  
  click(){
    // 向子组件传值
    this.child.getData(this.parentMsg)
  }
}