angular父子组件通信

父组件

根据组件名找到组件

<app-home-event [tableData]="family" (familyPhone)="receiveFamilyPhone($event)"></app-home-event>

传递参数一定要在暴露的事件中添加$event对象,否则无法获取参数

传数据给子组件,接受子组件的事件

import {Component, OnInit, OnDestroy} from '@angular/core';
import {FormControl} from '@angular/forms';
import {HttpInterceptorService} from '../../../utils/http-interceptor.service';

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

  // 模拟传入给子组件的数据
  public family = [{
    name: 'huangbiao',
    age: 29
  }, {
    name: 'liumei',
    age: 30
  }, {
    name: 'huanghaili',
    age: 4
  }]

  receiveFamilyPhone (familyStr: string) {
    console.dir(arguments);
    alert(familyStr);
  }
}

子组件

模板渲染父组件传递过来的数据

<div>
  <table class="table">
    <thead>
      <tr>
        <th scope="col">name</th>
        <th scope="col">age</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let person of tableData">
        <td scope="row">{{person.name}}</td>
        <td>{{person.age}}</td>
      </tr>
    </tbody>
  </table>

  <button class="btn btn-primary" (click)="emitAction()" type="submit">
    <i class="icon iconfont icon-clearall"></i>
    Clear
  </button>
</div>

子组件接收属性触发父组件事件

  1. @Input() 表示从父节点获取属性
  2. @Output() 表示从子节点传事件给父组件
import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';

@Component({
  selector: 'app-home-event',
  templateUrl: './home-event.component.html',
  styleUrls: ['./home-event.component.scss']
})
export class HomeEventComponent implements OnInit {
  @Input() tableData: object;
  @Output() familyPhone = new EventEmitter();

  constructor() {
    // 构造函数还无法获取父组件传递过来的数据,因为还没有完成组件的赋值动作
    // 官方解释:在指令的构造函数完成之前,那些被绑定的输入属性还都没有值。
    console.dir(this.tableData);
  }

  ngOnInit() {
    console.dir(this.tableData);
  }

  emitAction () {
    const backStr = JSON.stringify(this.tableData);
    alert('emitAction : ' + backStr);
    // 暴露familyPhone事件,并且传递参数backStr;注意,在付模板中的参数一定要带$event
    this.familyPhone.emit(backStr);
  }

}

@Output() familyPhone 表示当前组件对外暴露的事件名是familyPhone,通过 emit(参数)方法触发父组件的方法

猜你喜欢

转载自blog.csdn.net/hbiao68/article/details/83904323