【发布时间】:2018-12-17 15:02:36
【问题描述】:
我正在制作一个弹出式组件,我想在我的几个其他组件中使用它,所以我制作了一个 popup.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>
它像一个魅力一样加载,问题在于关闭它。关闭按钮位于 PopupComponent 上,是否有一种有效的方法让子组件 (PopupComponent) 影响父组件中的变量,即。 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 上得到“无法读取未定义的属性”,我无法声明它,语法似乎有点棘手。
问题仍然存在,我需要一个函数来加载组件,与 .destroy() 相反,如果可能的话,我更喜欢它而不是使用 *ngIf 加载和销毁。
编辑:仅通过在服务中使用布尔值作为 *ngIf 的触发器来部分解决它,还有没有办法在组件上执行函数加载和销毁?
【问题讨论】:
标签: javascript angular components