首页 > 技术文章 > angular 子组件与父组件通讯

hibiscus-ben 2018-12-29 15:35 原文

1. 子组件app-sidebar.compnent.html

(click)="goProject()"设置点击事件
  <mat-list-item [routerLink]="['/project']" (click)="goProject()">
    ....
  </mat-list-item>

 

2. 子组件app-sidebar.component.ts

用EventEmitter()方法向父级输出信息。

import { Component, OnInit, Output, EventEmitter } from '@angular/core';
@Component({
  selector: 'app-sidebar',
  templateUrl: './sidebar.component.html',
  styleUrls: ['']
})
export class SidebarComponent implements OnInit {

  @Output() closeSide = new EventEmitter<void>();
  constructor() { }

  goProject(){
  // 这里可以传参
this.closeSide.emit("data"); } }

3. 父组件app.component.html接收到closeSide方法。

// 没有参数的时候

<app-sidebar (closeSide)="drawer.toggle()"></app-sidebar>

// 需要接收传参的时候,一定要加上$event
<app-sidebar (closeSide)="toggle($event)"></app-sidebar>

toggle(data){
  console.log(data); // 'data'
}

 

推荐阅读