Angular 2.0 및 Modal 대화 상자
Angular 2.0에서 Confirmation modal 대화상자를 수행하는 방법에 대한 몇 가지 예를 찾고 있습니다.저는 Angular 1.0에 대한 Bootstrap 대화상자를 사용하고 있지만 Angular 2.0에 대한 예를 웹에서 찾을 수 없습니다.각진 2.0 문서도 확인했지만, 운이 없었습니다.
Angular 2.0으로 부트스트랩 대화상자를 사용할 수 있는 방법이 있습니까?
- 각도 2 이상
- 부트스트랩 CSS(애니메이션 보존)
- JQuery 없음
- 부트스트랩.js 없음
- 사용자 지정 모달 콘텐츠 지원(승인된 답변과 동일)
- 최근에 여러 모델에 대한 지원이 서로 겹쳐 추가되었습니다.
`
@Component({
selector: 'app-component',
template: `
<button type="button" (click)="modal.show()">test</button>
<app-modal #modal>
<div class="app-modal-header">
header
</div>
<div class="app-modal-body">
Whatever content you like, form fields, anything
</div>
<div class="app-modal-footer">
<button type="button" class="btn btn-default" (click)="modal.hide()">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</app-modal>
`
})
export class AppComponent {
}
@Component({
selector: 'app-modal',
template: `
<div (click)="onContainerClicked($event)" class="modal fade" tabindex="-1" [ngClass]="{'in': visibleAnimate}"
[ngStyle]="{'display': visible ? 'block' : 'none', 'opacity': visibleAnimate ? 1 : 0}">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<ng-content select=".app-modal-header"></ng-content>
</div>
<div class="modal-body">
<ng-content select=".app-modal-body"></ng-content>
</div>
<div class="modal-footer">
<ng-content select=".app-modal-footer"></ng-content>
</div>
</div>
</div>
</div>
`
})
export class ModalComponent {
public visible = false;
public visibleAnimate = false;
public show(): void {
this.visible = true;
setTimeout(() => this.visibleAnimate = true, 100);
}
public hide(): void {
this.visibleAnimate = false;
setTimeout(() => this.visible = false, 300);
}
public onContainerClicked(event: MouseEvent): void {
if ((<HTMLElement>event.target).classList.contains('modal')) {
this.hide();
}
}
}
배경을 보여주기 위해서는 다음과 같은 CSS가 필요합니다.
.modal {
background: rgba(0,0,0,0.6);
}
이제 이 예제에서는 여러 개의 모델을 동시에 사용할 수 있습니다.(자세한 내용은onContainerClicked()방법)을 선택합니다.
Bootstrap 4 CSS 사용자의 경우 CSS 클래스 이름이 Bootstrap 3에서 업데이트되었기 때문에 1개의 사소한 변경을 해야 합니다.다음 줄:[ngClass]="{'in': visibleAnimate}".[ngClass]="{'show': visibleAnimate}"
시연을 위해, 여기 플런커가 있습니다.
여기 GitHub의 Angular2 앱 내에서 부트스트랩 모달을 사용하는 방법에 대한 꽤 괜찮은 예가 있습니다.
요점은 부트스트랩 html과 jquery 초기화를 구성 요소로 래핑할 수 있다는 것입니다.재사용할 수 있는 시스템을 만들었습니다.modal템플릿 변수를 사용하여 열기를 트리거할 수 있는 구성 요소입니다.
<button type="button" class="btn btn-default" (click)="modal.open()">Open me!</button>
<modal #modal>
<modal-header [show-close]="true">
<h4 class="modal-title">I'm a modal!</h4>
</modal-header>
<modal-body>
Hello World!
</modal-body>
<modal-footer [show-default-buttons]="true"></modal-footer>
</modal>
당신은 npm 패키지를 설치하고 앱 모듈에 모달 모듈을 등록하기만 하면 됩니다.
import { Ng2Bs3ModalModule } from 'ng2-bs3-modal/ng2-bs3-modal';
@NgModule({
imports: [Ng2Bs3ModalModule]
})
export class MyAppModule {}
이것은 각도 2를 제외한 jquery나 다른 라이브러리에 의존하지 않는 간단한 접근 방식입니다.아래 구성 요소(errorMessage.ts)는 다른 구성 요소의 하위 보기로 사용할 수 있습니다.이것은 항상 열려 있거나 표시되는 부트스트랩 모달에 불과합니다.가시성은 ngIf 문에 의해 결정됩니다.
errorMessage.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-error-message',
templateUrl: './app/common/errorMessage.html',
})
export class ErrorMessage
{
private ErrorMsg: string;
public ErrorMessageIsVisible: boolean;
showErrorMessage(msg: string)
{
this.ErrorMsg = msg;
this.ErrorMessageIsVisible = true;
}
hideErrorMsg()
{
this.ErrorMessageIsVisible = false;
}
}
errorMessage.html
<div *ngIf="ErrorMessageIsVisible" class="modal fade show in danger" id="myModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Error</h4>
</div>
<div class="modal-body">
<p>{{ErrorMsg}}</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" (click)="hideErrorMsg()">Close</button>
</div>
</div>
</div>
</div>
다음은 상위 컨트롤의 예입니다(간단히 설명하기 위해 일부 비관련 코드는 생략됨).
부모.ts
import { Component, ViewChild } from '@angular/core';
import { NgForm } from '@angular/common';
import {Router, RouteSegment, OnActivate, ROUTER_DIRECTIVES } from '@angular/router';
import { OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
@Component({
selector: 'app-application-detail',
templateUrl: './app/permissions/applicationDetail.html',
directives: [ROUTER_DIRECTIVES, ErrorMessage] // Note ErrorMessage is a directive
})
export class ApplicationDetail implements OnActivate
{
@ViewChild(ErrorMessage) errorMsg: ErrorMessage; // ErrorMessage is a ViewChild
// yada yada
onSubmit()
{
let result = this.permissionsService.SaveApplication(this.Application).subscribe(x =>
{
x.Error = true;
x.Message = "This is a dummy error message";
if (x.Error) {
this.errorMsg.showErrorMessage(x.Message);
}
else {
this.router.navigate(['/applicationsIndex']);
}
});
}
}
부모님.
<app-error-message></app-error-message>
// your html...
이제 NPM 패키지로 사용 가능
@스티븐 폴은 계속...
- Angular 2 이상 부트스트랩 CSS(애니메이션 보존)
- JQuery 없음
- 부트스트랩.js 없음
- 맞춤형 모달 콘텐츠 지원
- 여러 모델을 서로 겹쳐 지원합니다.
- 모듈화됨
- 모달이 열려 있을 때 스크롤 사용 안 함
- 이동 중 모달이 파괴됩니다.
- 게으른 콘텐츠 초기화로 인해
ngOnDestroy(ed) 모달이 종료된 경우. - 모달이 표시되면 상위 스크롤이 비활성화됨
레이지 콘텐츠 초기화
왜요?
경우에 따라 닫힌 후 상태를 유지하기 위해 모달을 사용하지 않고 초기 상태로 복원할 수 있습니다.
원본 모달 발행
컨텐츠를 보기로 바로 전달하면 실제로 모달이 컨텐츠를 가져오기도 전에 초기화를 생성합니다.모달은 사용하더라도 그러한 콘텐츠를 죽일 수 있는 방법을 사용하더라도*ngIf포장지
해결책
ng-template.ng-template명령이 내려질 때까지 렌더링되지 않습니다.
my-component.s.t.s.
...
imports: [
...
ModalModule
]
마이컴포넌트.츠
<button (click)="reuseModal.open()">Open</button>
<app-modal #reuseModal>
<ng-template #header></ng-template>
<ng-template #body>
<app-my-body-component>
<!-- This component will be created only when modal is visible and will be destroyed when it's not. -->
</app-my-body-content>
<ng-template #footer></ng-template>
</app-modal>
modal.component.ts
export class ModalComponent ... {
@ContentChild('header') header: TemplateRef<any>;
@ContentChild('body') body: TemplateRef<any>;
@ContentChild('footer') footer: TemplateRef<any>;
...
}
modal.component.component.cisco
<div ... *ngIf="visible">
...
<div class="modal-body">
ng-container *ngTemplateOutlet="body"></ng-container>
</div>
레퍼런스
저는 인터넷에 관한 훌륭한 공식 및 커뮤니티 문서가 없었다면 불가능했을 것이라고 말할 수 밖에 없습니다.당신들 중 일부는 어떻게 하면 더 잘 이해할 수 있을지도 모릅니다.ng-template,*ngTemplateOutlet그리고.@ContentChild일하다.
https://angular.io/api/common/NgTemplateOutlet
https://blog.angular-university.io/angular-ng-template-ng-container-ngtemplateoutlet/
https://medium.com/claritydesignsystem/ng-content-the-hidden-docs-96a29d70d11b
https://netbasal.com/understanding-viewchildren-contentchildren-and-querylist-in-angular-896b0c689f6e
https://netbasal.com/understanding-viewchildren-contentchildren-and-querylist-in-angular-896b0c689f6e
전체 복사 붙여넣기 솔루션
modal.component.component.cisco
<div
(click)="onContainerClicked($event)"
class="modal fade"
tabindex="-1"
[ngClass]="{'in': visibleAnimate}"
[ngStyle]="{'display': visible ? 'block' : 'none', 'opacity': visibleAnimate ? 1 : 0}"
*ngIf="visible">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<ng-container *ngTemplateOutlet="header"></ng-container>
<button class="close" data-dismiss="modal" type="button" aria-label="Close" (click)="close()">×</button>
</div>
<div class="modal-body">
<ng-container *ngTemplateOutlet="body"></ng-container>
</div>
<div class="modal-footer">
<ng-container *ngTemplateOutlet="footer"></ng-container>
</div>
</div>
</div>
</div>
modal.component.ts
/**
* @Stephen Paul https://stackoverflow.com/a/40144809/2013580
* @zurfyx https://stackoverflow.com/a/46949848/2013580
*/
import { Component, OnDestroy, ContentChild, TemplateRef } from '@angular/core';
@Component({
selector: 'app-modal',
templateUrl: 'modal.component.html',
styleUrls: ['modal.component.scss'],
})
export class ModalComponent implements OnDestroy {
@ContentChild('header') header: TemplateRef<any>;
@ContentChild('body') body: TemplateRef<any>;
@ContentChild('footer') footer: TemplateRef<any>;
public visible = false;
public visibleAnimate = false;
ngOnDestroy() {
// Prevent modal from not executing its closing actions if the user navigated away (for example,
// through a link).
this.close();
}
open(): void {
document.body.style.overflow = 'hidden';
this.visible = true;
setTimeout(() => this.visibleAnimate = true, 200);
}
close(): void {
document.body.style.overflow = 'auto';
this.visibleAnimate = false;
setTimeout(() => this.visible = false, 100);
}
onContainerClicked(event: MouseEvent): void {
if ((<HTMLElement>event.target).classList.contains('modal')) {
this.close();
}
}
}
모달 . 모달 .
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ModalComponent } from './modal.component';
@NgModule({
imports: [
CommonModule,
],
exports: [ModalComponent],
declarations: [ModalComponent],
providers: [],
})
export class ModalModule { }
저는 프로젝트에 ngx-bootstrap을 사용합니다.
데모는 여기에서 확인할 수 있습니다.
깃허브가 여기 있습니다.
사용 방법:
모듈로 가져오기
// RECOMMENDED (doesn't work with system.js) import { ModalModule } from 'ngx-bootstrap/modal'; // or import { ModalModule } from 'ngx-bootstrap'; @NgModule({ imports: [ModalModule.forRoot(),...] }) export class AppModule(){}
- 단순 정적 모달
<button type="button" class="btn btn-primary" (click)="staticModal.show()">Static modal</button> <div class="modal fade" bsModal #staticModal="bs-modal" [config]="{backdrop: 'static'}" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true"> <div class="modal-dialog modal-sm"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title pull-left">Static modal</h4> <button type="button" class="close pull-right" aria-label="Close" (click)="staticModal.hide()"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body"> This is static modal, backdrop click will not close it. Click <b>×</b> to close modal. </div> </div> </div> </div>
다음은 모달 부트스트랩 앵글2 구성 요소를 완전히 구현한 것입니다.
메인 html 파일에 합니다.<html>그리고.<body>태그의 맨 .<body>가지고 있는 태그:
<script src="assets/js/jquery-2.1.1.js"></script>
<script src="assets/js/bootstrap.min.js"></script>
modal.component.ts:
import { Component, Input, Output, ElementRef, EventEmitter, AfterViewInit } from '@angular/core';
declare var $: any;// this is very importnant (to work this line: this.modalEl.modal('show')) - don't do this (becouse this owerride jQuery which was changed by bootstrap, included in main html-body template): let $ = require('../../../../../node_modules/jquery/dist/jquery.min.js');
@Component({
selector: 'modal',
templateUrl: './modal.html',
})
export class Modal implements AfterViewInit {
@Input() title:string;
@Input() showClose:boolean = true;
@Output() onClose: EventEmitter<any> = new EventEmitter();
modalEl = null;
id: string = uniqueId('modal_');
constructor(private _rootNode: ElementRef) {}
open() {
this.modalEl.modal('show');
}
close() {
this.modalEl.modal('hide');
}
closeInternal() { // close modal when click on times button in up-right corner
this.onClose.next(null); // emit event
this.close();
}
ngAfterViewInit() {
this.modalEl = $(this._rootNode.nativeElement).find('div.modal');
}
has(selector) {
return $(this._rootNode.nativeElement).find(selector).length;
}
}
let modal_id: number = 0;
export function uniqueId(prefix: string): string {
return prefix + ++modal_id;
}
modal.sys:
<div class="modal inmodal fade" id="{{modal_id}}" tabindex="-1" role="dialog" aria-hidden="true" #thisModal>
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header" [ngClass]="{'hide': !(has('mhead') || title) }">
<button *ngIf="showClose" type="button" class="close" (click)="closeInternal()"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<ng-content select="mhead"></ng-content>
<h4 *ngIf='title' class="modal-title">{{ title }}</h4>
</div>
<div class="modal-body">
<ng-content></ng-content>
</div>
<div class="modal-footer" [ngClass]="{'hide': !has('mfoot') }" >
<ng-content select="mfoot"></ng-content>
</div>
</div>
</div>
</div>
클라이언트 Editor 구성 요소의 사용 예: client-edit-component.ts:
import { Component } from '@angular/core';
import { ClientService } from './client.service';
import { Modal } from '../common';
@Component({
selector: 'client-edit',
directives: [ Modal ],
templateUrl: './client-edit.html',
providers: [ ClientService ]
})
export class ClientEdit {
_modal = null;
constructor(private _ClientService: ClientService) {}
bindModal(modal) {this._modal=modal;}
open(client) {
this._modal.open();
console.log({client});
}
close() {
this._modal.close();
}
}
client-edit.dll:
<modal [title]='"Some standard title"' [showClose]='true' (onClose)="close()" #editModal>{{ bindModal(editModal) }}
<mhead>Som non-standart title</mhead>
Some contents
<mfoot><button calss='btn' (click)="close()">Close</button></mfoot>
</modal>
이죠.title,showClose,<mhead>그리고.<mfoot> 매개 tags.ar 이름/파일 이름
런타임에 생성되는 ASUI 대화 상자를 선택합니다.논리를 숨기고 보여줄 필요가 없습니다.Simply service는 AOT ASUI NPM을 사용하여 런타임에 구성 요소를 생성합니다.
ng-window를 사용하려고 하면 개발자가 간단한 방법으로 단일 페이지 응용 프로그램에서 여러 개의 창을 열고 전체 제어할 수 있습니다. Jquery, Bootstrap은 없습니다.
사용 가능한 구성
- 최대화 창
- 창 최소화
- 사용자 정의 크기,
- 사용자 지정 위치
- 창을 끌 수 있습니다.
- 상위 창 차단 여부
- 창 가운데 맞춤
- 값을 child 창으로 전달
- 하위 창에서 상위 창으로 값 전달
- 상위 창에서 하위 창 닫기 듣기
- 사용자 지정 수신기를 사용하여 이벤트 크기 조정 듣기
- 최대 크기로 열기 또는 열기
- 창 크기 조정 사용 및 사용 안 함
- 최대화 사용 및 사용 안 함
- 최소화 사용 및 사용 안 함
Angular 7 + NgBootstrap
주요 구성 요소에서 모달을 열고 결과를 다시 전달하는 간단한 방법이 제가 원했던 것입니다.저는 처음부터 새로운 프로젝트를 만들고, ngbootstrap을 설치하고, Modal을 만드는 단계별 튜토리얼을 만들었습니다.복제하거나 안내에 따라 복제할 수 있습니다.
이것이 Angular에 새로운 도움이 되기를 바랍니다.!
https://github.com/wkaczurba/modal-demo
세부사항:
모달-모달 템플릿(modal-modal.component.modal):
<ng-template #content let-modal>
<div class="modal-header">
<h4 class="modal-title" id="modal-basic-title">Are you sure?</h4>
<button type="button" class="close" aria-label="Close" (click)="modal.dismiss('Cross click')">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>You have not finished reading my code. Are you sure you want to close?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline-dark" (click)="modal.close('yes')">Yes</button>
<button type="button" class="btn btn-outline-dark" (click)="modal.close('no')">No</button>
</div>
</ng-template>
modal-simple.component.ts:
import { Component, OnInit, ViewChild, Output, EventEmitter } from '@angular/core';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
@Component({
selector: 'app-modal-simple',
templateUrl: './modal-simple.component.html',
styleUrls: ['./modal-simple.component.css']
})
export class ModalSimpleComponent implements OnInit {
@ViewChild('content') content;
@Output() result : EventEmitter<string> = new EventEmitter();
constructor(private modalService : NgbModal) { }
open() {
this.modalService.open(this.content, {ariaLabelledBy: 'modal-simple-title'})
.result.then((result) => { console.log(result as string); this.result.emit(result) },
(reason) => { console.log(reason as string); this.result.emit(reason) })
}
ngOnInit() {
}
}
Demo of it(app.component.html) - 반환 이벤트를 처리하는 간단한 방법:
<app-modal-simple #mymodal (result)="onModalClose($event)"></app-modal-simple>
<button (click)="mymodal.open()">Open modal</button>
<p>
Result is {{ modalCloseResult }}
</p>
app.component.ts - onModalClosed는 모달이 닫히면 실행됩니다.
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
modalCloseResult : string;
title = 'modal-demo';
onModalClose(reason : string) {
this.modalCloseResult = reason;
}
}
건배.
언급URL : https://stackoverflow.com/questions/34513558/angular-2-0-and-modal-dialog
'programing' 카테고리의 다른 글
| 기존 Git 저장소를 다른 저장소로 가져오는 방법은 무엇입니까? (0) | 2023.04.29 |
|---|---|
| WPF의 페이지 대 창? (0) | 2023.04.29 |
| 여기서 ${EXECUTABLE_NAME} 및 ${PRODUCT_NAME}은(는) 정의됩니다. (0) | 2023.04.29 |
| UIScrollView 내부의 UIWebView를 확대하려면 어떻게 해야 합니까? (0) | 2023.04.29 |
| 공식 C# 드라이버를 사용하여 Mongo DB에서 시작 (0) | 2023.04.29 |
