简体   繁体   English

如何隐藏 ngx-bootstrap 模态而不破坏模态组件?

[英]How to hide ngx-bootstrap modal without destroy the modal component?

Is there a way to hide BsModal without destroying the modal's component?有没有办法在不破坏模态组件的情况下隐藏 BsModal ? What I would like to achieve is that, once the modal is shown the first time, it doesn't recreate MyComponent every time is hide/shown again.我想要实现的是,一旦第一次显示模式,它不会重新创建 MyComponent 每次都隐藏/再次显示。 Once it is build the first time is just a matter of showing or not to the user and not rebuilding the whole component.一旦第一次构建,只是向用户显示或不显示的问题,而不是重建整个组件。

I need this because I would like to provide a service in the MyComponent providers and I expect the same instance of that service if I close and reopen the modal.我需要这个,因为我想在 MyComponent 提供程序中提供服务,并且如果我关闭并重新打开模式,我希望该服务的相同实例。

I have a component:我有一个组件:

@Component({
  selector: 'my-component',
  template: '<p>Hi from my component</p>'
})
export class MyComponent implements OnInit {

  ngOnInit(): void {
    console.log('want to show this message only once');
  }
}

I'm using ngx-bootstrap modal to show this component我正在使用 ngx-bootstrap 模式来显示这个组件

export class AnotherComponent() {

  private modalRef: BsModalRef;

  constructor(private modalService: BsModalService) {}

  showModal(): void {
    this.modalService.show(MyComponent);
  }

  hideModal(): void {
    this.modalRef.hide();
  }
}

I would like to have ngOnInit() executed only the first time the modal is open.我希望 ngOnInit() 仅在第一次打开模式时执行。

So, what you are wanting might not be possible until the Ivy renderer is in production (see https://github.com/angular/angular/issues/19812 ).因此,在 Ivy 渲染器投入生产之前,您想要的可能无法实现(请参阅https://github.com/angular/angular/issues/19812 )。 The current renderer uses either a TemplateRef or component reference to create the content for a dynamically created component (see https://angular.io/guide/dynamic-component-loader ).当前渲染器使用TemplateRef或组件引用来为动态创建的组件创建内容(请参阅https://angular.io/guide/dynamic-component-loader )。 Each time this is run, the component/template is re-initialized.每次运行时,组件/模板都会重新初始化。

This is not a problem though.不过,这不是问题。 If you have some piece of static data, store that in a singleton service (the services that use {providedIn: "root"} ) and then when the component is initialized, pull that data from the component.如果您有一些 static 数据,请将其存储在 singleton 服务(使用{providedIn: "root"}的服务)中,然后在初始化组件时,从组件中提取该数据。 Ngx-bootstrap is using the same code Angular uses to create components at run-time. Ngx-bootstrap 使用 Angular 用于在运行时创建组件的相同代码。 This is not a performance hit to rerun the component unless you are doing something heavy in the initialization phase.除非您在初始化阶段执行繁重的工作,否则重新运行组件不会对性能造成影响。 If you are, off-load that to a service and pull the results every time the component is created.如果是,请将其卸载到服务并在每次创建组件时提取结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM