Angular 2 模态对话框

Muhammad Adil 2023年1月30日
  1. 什么是 Angular 2 中的模态对话框
  2. 导入库以在 Angular 2 中创建模态对话框
  3. 在 Angular 2 中创建模态对话框的模态服务
  4. 自定义模态组件以在 Angular 2 中创建模态对话框
Angular 2 模态对话框

Angular 2.0 是流行的 JavaScript 框架的最新版本。它为开发人员提供了一种新的基于组件的架构,支持移动设备,并且是用 TypeScript 编写的。

模态对话框是在当前窗口顶部弹出并阻止交互直到关闭的窗口。本文将详细解释 Angular 2.0 模态对话框。

什么是 Angular 2 中的模态对话框

为了帮助开发人员创建更具动态性和交互性的 Web 应用程序,Angular 2.0 引入了一个名为 Modal Dialog 的新组件。

术语 modal dialogmodal window 可能看起来令人困惑,但事实并非如此。大多数人默认将模态窗口称为弹出窗口。

模态对话框使开发人员能够创建具有丰富内容和动画的各种对话框。它可以以不同的方式使用,例如:

  1. 通过要求输入来提示用户。
  2. 显示重要消息或通知。
  3. 显示错误信息或确认信息。

点击这里如果你想了解更多关于模态对话框的信息。

为简单起见,让我们将工作分为以下几部分。

  1. 添加库
  2. 模态服务
  3. 模态组件

出于造型目的,我们使用了 Bootstrap。

导入库以在 Angular 2 中创建模态对话框

index.html 文件中导入以下库以增强代码的功能。

<script src="https://npmcdn.com/core-js/client/shim.min.js"></script>
        <link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">

    <script src="https://npmcdn.com/zone.js@0.6.12?main=browser"></script>
    <script src="https://npmcdn.com/reflect-metadata@0.1.3"></script>
    <script src="https://npmcdn.com/systemjs@0.19.27/dist/system.src.js"></script>

在此之后,我们主要关心的是编译代码。你不能用 Angular 2 直接将东西编译到 DOM;你需要一个占位符。

这就是我们制作 modal placeholder 的原因。请记住,这是开始的最重要步骤。

@Component({
    selector: "modal-placeholder",
    template: `<div #modalplaceholder></div>`
})
export class ModalPlaceholderComponent implements OnInit {
    @ViewChild("modalplaceholder", {read: ViewContainerRef}) viewContainerRef;

在 Angular 2 中创建模态对话框的模态服务

我们正在迈向第二步,也称为根步。模态服务的主要目的是使页面和模态组件更容易通信。

模态服务还跟踪哪些页面模态可用以及如何与它们交互。

import {Component,NgModule, ViewChild, OnInit, ViewContainerRef, Compiler, ReflectiveInjector, Injectable, Injector, ComponentRef} from "@angular/core";
import {Observable, Subject, BehaviorSubject, ReplaySubject} from "rxjs/Rx";

@Injectable()
export class ModalService {
    private vcRef: ViewContainerRef;
    private injector: Injector;
    public activeInstances: number;

    constructor(private compiler: Compiler) {
    }

    registerViewContainerRef(vcRef: ViewContainerRef): void {
        this.vcRef = vcRef;
    }

    registerInjector(injector: Injector): void {
        this.injector = injector;
    }

    create<T>(module: any, component: any, parameters?: Object): Observable<ComponentRef<T>> {
        let componentRef$ = new ReplaySubject();
        this.compiler.compileModuleAndAllComponentsAsync(module)
            .then(factory => {
                let componentFactory = factory.componentFactories.filter(item => item.componentType === component)[0];
                const childInjector = ReflectiveInjector.resolveAndCreate([], this.injector);
                let componentRef = this.vcRef.createComponent(componentFactory, 0, childInjector);
                Object.assign(componentRef.instance, parameters);
                this.activeInstances ++;
                componentRef.instance["com"] = this.activeInstances;
                componentRef.instance["destroy"] = () => {
                    this.activeInstances --;
                    componentRef.destroy();
                };
                componentRef$.next(componentRef);
                componentRef$.complete();
            });
        return <Observable<ComponentRef<T>>> componentRef$.asObservable();
    }
}

@Component({
    selector: "modal-placeholder",
    template: `<div #modalplaceholder></div>`
})
export class ModalPlaceholderComponent implements OnInit {
    @ViewChild("modalplaceholder", {read: ViewContainerRef}) viewContainerRef;

    constructor(private modalService: ModalService, private injector: Injector) {

    }
    ngOnInit(): void {
        this.modalService.registerViewContainerRef(this.viewContainerRef);
        this.modalService.registerInjector(this.injector);
    }
}


@NgModule({
    declarations: [ModalPlaceholderComponent],
    exports: [ModalPlaceholderComponent],
    providers: [ModalService]
})
export class ModalModule {
}

export class ModalContainer {
    destroy: Function;
    componentIndex: number;
    closeModal(): void {
        this.destroy();
    }
}
export function Modal() {
    return function (world) {
        Object.assign(world.prototype,  ModalContainer.prototype);
    };
}

什么是 RxJS

RxJS(JavaScript 的响应式扩展)是一套模块,允许你使用可见数组和组合在 JavaScript 中创建异步和基于事件的程序。

自定义模态组件以在 Angular 2 中创建模态对话框

自定义模态指令可以使用 <modal> 标签在 Angular 应用程序中添加模态。

当一个模态实例加载时,它会向 ModalService 注册,以便该服务可以打开和关闭模态窗口。当使用 Destroy 方法销毁时,它会从 ModalService 注销。

import {Modal} from "./modal.module";
import {Component} from "@angular/core";
@Component({
    selector: "my-cust",
    template: `
        <h1>Basic Components of a Car</h1>
        <button (click)="onDelete()">×</button>
        <ul>
          <li *ngFor="let option of options">{{option}}</li>
        </ul>
        <div>
            <button (click)="onDelete()">
                <span>Delete</span>
            </button>
            <button (click)="onSave()">
                <span>Save</span>
            </button>
        </div>
`
})
@Modal()
export class ModalComponent {
    ok: Function;
    destroy: Function;
    closeModal: Function;
    options = ["Speed", "Mileage", "Color"];

    onDelete(): void{
        this.closeModal();
        this.destroy();
    }

    onSave(): void{
        this.closeModal();
        this.destroy();
        this.ok(this.options);
    }
}

最后,index.html 代码如下。

<!DOCTYPE html>
<html>
  <head>
    <title>Angular 2 QuickStart</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- 1. Load libraries -->
     <!-- Polyfill(s) for older browsers -->
    <script src="https://npmcdn.com/core-js/client/shim.min.js"></script>
        <link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">

    <script src="https://npmcdn.com/zone.js@0.6.12?main=browser"></script>
    <script src="https://npmcdn.com/reflect-metadata@0.1.3"></script>
    <script src="https://npmcdn.com/systemjs@0.19.27/dist/system.src.js"></script>

    <!-- 2. Configure SystemJS -->
    <script src="config.js"></script>
    <script>
      System.import('app').catch(function(err){ console.error(err); });
    </script>
  </head>

  <body>
    <my-hoop>Loading...</my-hoop>
  </body>
</html>

因此,这就是在 Angular 2 中创建模态的方式。代码可维护、灵活且易于使用。点击这里查看代码的演示。

作者: Muhammad Adil
Muhammad Adil avatar Muhammad Adil avatar

Muhammad Adil is a seasoned programmer and writer who has experience in various fields. He has been programming for over 5 years and have always loved the thrill of solving complex problems. He has skilled in PHP, Python, C++, Java, JavaScript, Ruby on Rails, AngularJS, ReactJS, HTML5 and CSS3. He enjoys putting his experience and knowledge into words.

Facebook