angular - 在 Angular2/4 中加载组件

标签 angular ngx-bootstrap

我正在用 Angular 4 创建一个应用程序,我想要一个加载组件,这样用户就可以意识到他提交了一个表单,应用程序正在做某事,并且应用程序正在等待来自后端的信息。

我在 angularjs 中通过加载器组件并使用 $rootScope 共享隐藏或显示的操作来做到这一点...但是在 angular2/4 中我不知道如何做到这一点。

理想情况下,我需要一个加载组件,该组件将覆盖表单或页面的某些部分(当检索属于该部分的信息时)或可能覆盖整个屏幕。

能否请您提供有关如何执行此操作的线索?

谢谢!

最佳答案

您需要创建一个加载服务,该服务可以存储对您的加载组件的引用。然后在需要能够切换该加载组件的其他组件的构造函数中注入(inject)该加载服务。

import { Injectable } from '@angular/core';
import { LoadingComponent } from './loading.component';

@Injectable()
export class LoadingService {
  private instances: {[key: string]: LoadingComponent} = {};

  public registerInstance(name: string, instance: LoadingComponent) {  
    this.instances[name] = instance;
  }

  public removeInstance(name: string, instance: LoadingComponent) {
    if (this.instances[name] === instance) {
      delete this.instances[name];
    }
  }

  public hide(name: string) {
    this.instances[name].hide();
  }

  public show(name: string) {
    this.instances[name].show();
  }
}

请务必在模块的 providers 数组中注册您的 LoadingService!

然后在 LoadingComponent 中,您可以注入(inject) LoadingService,这样 LoadingComponent 就可以向 LoadingService 注册自己> 它应该向该服务注册自己:

import { Component, OnInit, Input, OnDestroy } from '@angular/core';
import { LoadingService } from './loading.service';

@Component({
  selector: 'yourapp-loading',
  templateUrl: './loading.component.html',
  styleUrls: ['./loading.component.scss']
})
export class LoadingComponent implements OnInit, OnDestroy {
  @Input() name: string;
  private isVisible = false;

  constructor(private service: LoadingService) {}

  ngOnInit() {
    if (this.name) {
      this.service.registerInstance(this.name, this);
    }
  }

  ngOnDestroy() {
    if (this.name) {
      this.service.removeInstance(this.name, this);
    }
  }

  /* ... code to show/hide this component */
}

关于angular - 在 Angular2/4 中加载组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45597039/

相关文章:

javascript - Angular 8 : Assign Date Values to Type Moment

Angular8 ngx-bootstrap 不使用 --prod 编译

javascript - ngx-bootstrap for angular - datepicker 如何在似乎没有任何效果时更改主题颜色

angular - ngx-bootstrap 和 ng2 bootstrap 之间的区别?

Angular Material 2 Table Mat Row Click 事件也通过在 Mat Cell 中单击按钮来调用

javascript - Navigator angular 13 类型上不存在 msSaveOrOpenBlob 属性

javascript - 如何在 Angular2 的模板 html 上呈现动态创建的数组组件?

javascript - 解析完整的json文件 typescript

angular - ngx-bootstrap 预输入更改检测问题

javascript - 如何将自定义 HTML 添加到 ngx Typeahead?