【Angular】父組件監聽子組件事件(傳參)


Angular官方文檔Demo地址:>component-interaction#parent-listens-for-child-event

舉一個自己在寫的項目🌰

子組件 imageupload 中的一個事件 onCropped(e:ImgCropperEvent)

onCropped(e: ImgCropperEvent) {
    this.croppedImage = e.dataURL;
    console.log("cropped img: ", e);
    // console.log("dataURL", e.dataURL);
    this.imgurl = e.dataURL;
    this.getImgUrl.emit(this.imgurl);
  }

目的:是想要在父組件中獲取到子組件的數據,我選擇了通過監聽事件的方法來傳遞。

用到的組件:

import {Output,EventEmitter} from "@angular/core";

 

@Output() getImgUrl = new EventEmitter<string>();

@Output() 聲明getImgUrl的同時輸出

 

子組件的CSS selector名:

 

 

父組件 使用該selector:

<app-images-editorbox (getImgUrl)="onGetImgUrl($event)"></app-images-editorbox>

 

當監聽到事件發生時會調用onGetImgUrl()事件處理, 事件參數(用 $event 表示)傳給事件處理方法。

 

onGetImgUrl(imgUrl: string) {
    this.imgUrl = imgUrl;
  }

 

畫個圖梳理一下:

 

 

 

 

當然了還有許多方法來進行組件之間的通訊,選擇合適的方法來進行開發。


免責聲明!

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



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