angular 子組件與父組件通訊


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'
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM