簡體   English   中英

Angular-發出的事件無法傳遞到父組件

[英]Angular - emitted event doesn't get through to parent component

我正在嘗試從子組件向父組件發出事件。 這是父文件TS文件的一部分:

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

@Component({
  selector: 'app-car-detail',
  templateUrl: './car-detail.component.html',
  styleUrls: ['./car-detail.component.css'],
})
export class CarDetailComponent implements OnInit {
  constructor() { }

  ngOnInit() {
    this.getCarDetail(this.route.snapshot.params['id']);
  }

  refreshList(event){
    console.log("Parent called");
  }
}

以及與發射器有關的模板的一部分

<app-operations (myEvent)="refreshList($event)"></app-operations>

這是子TS文件:

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


@Component({
  selector: 'app-add-operation',
  templateUrl: './add-operation.component.html',
  styleUrls: ['./add-operation.component.css']
})
export class AddOperationComponent implements OnInit {


  @Output() myEvent = new EventEmitter<any>();

  constructor() { }

  ngOnInit() {
  }

  callParent() {
    console.log('callparentmethod');
    this.myEvent.emit('eventDesc');
  }

}

和一個用於測試調用callParent方法的按鈕:

<button (click)="callParent()">call</button>

當我單擊按鈕時,可以看到調用了callParent方法,但是沒有觸發應在父級(refreshList)中觸發的方法。 我看了多個示例,但不明白為什么它不起作用。

您的視圖引用了錯誤的組件。 嘗試這個:

<app-add-operation (myEvent)="refreshList($event)"></app-add-operation>

事件發射器僅影響組件的直接父對象,因此您需要將事件從app-add-operation擴展到app-operation,再擴展到app-car-detail。

請參閱通過Angular2中的嵌套組件發出事件

請將此功能添加到您的子組件上。您可以參考此文檔組件交互

 myEvent(event: any) {
     console.log(event);
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM