【问题标题】:Angular - dynamically destroying a component, *ngIf and ComponentRefAngular - 动态销毁组件,*ngIf 和 ComponentRef
【发布时间】: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


    【解决方案1】:

    您可以将 EventEmitter() 绑定到您的组件以调用父组件中的函数。

    <app-popup [onClose]="load_popup = false" *ngIf="load_popup"></app-popup>
    

    然后在你的 app-popup 组件内部:

    @Output onClose = new EventEmitter();
    
    public closePopup(/* code emitted for brevity */) {
        /* code emitted for brevity */
        this.onClose.emit(); //Call the parent function (in this case: 'load_popup = false')
    }
    

    重要的是要知道您可以将整个函数传递给绑定函数,甚至可以将变量从子函数传回父函数:

    [onClose]="myFunction($event)"
    this.onClose.emit(DATA HERE);
    

    顺便说一句,因为您使用的是 Angular;我建议考虑使用 Modals 来弹出对话框。你可以在这里看到一个很好的例子:

    https://ng-bootstrap.github.io/#/components/modal/examples

    【讨论】:

    • 通过变量的传递和模态提示解决了我的问题以及对将来的使用有用!
    猜你喜欢
    • 1970-01-01
    • 2021-04-26
    • 2018-01-27
    • 2019-02-18
    • 1970-01-01
    • 2019-04-26
    • 2016-12-05
    • 2019-07-28
    • 1970-01-01
    相关资源
    最近更新 更多