我正在创建一个弹出组件,我想在其他几个组件中使用它,所以我创建了一个pop up.service,使组件能够通过其他组件内的*ngif加载。这给我带来了一个问题,因为PopupComponent是一个独立的实体,我不确定如何将数据从子组件(PopupComponent)传递到其各自的父组件。
atm在parentcomponent.ts中加载如下:
public openPopup(order_id: string, invoice_id: string): void{
this.load_popup=this.popupService.openPopup(order_id, "selected_order", invoice_id, "selected_invoice");
}
和parentcomponent.html:
<app-popup *ngIf="load_popup"></app-popup>
它就像一个魅力,问题在于关闭它。关闭按钮位于弹出组件上,是否有有效的方法让子组件(弹出组件)影响父组件IE中的变量。
ParentComponent.load_popup=false
?
我的另一个想法是动态加载组件,但是我不知道如何做。我在忙着使用PopupService,并在其中添加类似的内容:
import { Injectable, ComponentRef } from '@angular/core';
import {PopupComponent} from '../popup/popup.component';
@Injectable({
providedIn: 'root'
})
export class PopupService {
popup_ref: ComponentRef<PopupComponent>
constructor(
) { }
//Implemented in orderoverviewcomponent, invoicecomponent, and placeordercomponent
public openPopup(id1:string, storage_label1:string, id2:string, storage_label2:string): Boolean{
if (id1){
localStorage.setItem(storage_label1, JSON.stringify(id1));
}
if (id2){
localStorage.setItem(storage_label2, JSON.stringify(id2));
}
this.popup_ref.initiate(); //this line is a made up example of loading the component
return true;
}
public closePopup(storage_label1: string, storage_label2:string): Boolean{
if(storage_label1){
localStorage.removeItem(storage_label1);
}
if(storage_label2){
localStorage.removeItem(storage_label2);
}
this.popup_ref.destroy();
return false;
}
}
在哪里?
this.popup_ref.destroy();
理想情况下会破坏popupcomponent,但是当我这样做时,popup-ref上有一个“cannot read property of undefined”,我在声明它时遇到了问题,语法看起来有点复杂。
问题还在于,我需要一个函数来加载组件,与.destroy()相反,如果可能的话,我会更喜欢用*ngif加载和销毁组件。
编辑:通过在服务中使用一个布尔值作为*ngif的触发器,部分地解决了这个问题,有没有一种方法可以在组件上进行函数加载和销毁?