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의 모달 대화 상자란?

개발자가 보다 동적이고 대화형 웹 응용 프로그램을 만들 수 있도록 Angular 2.0은 Modal Dialog라는 새로운 구성 요소를 도입했습니다.

모달 대화 상자모달 창이라는 용어는 혼동되는 것처럼 보일 수 있지만 그렇지 않습니다. 대부분의 사람들은 기본적으로 모달 창을 팝업으로 참조합니다.

모달 대화 상자를 통해 개발자는 풍부한 콘텐츠와 애니메이션이 포함된 다양한 대화 상자를 만들 수 있습니다. 예를 들어 다음과 같이 다양한 방식으로 사용할 수 있습니다.

  1. 입력을 요청하여 사용자에게 프롬프트를 표시합니다.
  2. 중요한 메시지나 알림을 표시하기 위해.
  3. 오류 메시지 또는 확인 메시지를 표시합니다.

Modal Dialog에 대해 더 알고 싶다면 여기를 클릭하세요.

간단하게 작업을 다음과 같이 나누어 보겠습니다.

  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에 직접 컴파일할 수 없습니다. 자리 표시자가 필요합니다.

그래서 우리는 모달 자리 표시자를 만들었습니다. 이것이 시작하기 위한 가장 중요한 단계임을 명심하십시오.

@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’(Reactive Extensions for 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 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

관련 문장 - Angular Modal