我使用Angular 7(Example)创建了模态组件:
import { Component, ElementRef, Input, OnInit, OnDestroy, Renderer2, Inject } from '@angular/core';
import { ModalService } from './modal.service';
@Component({
selector: 'modal',
templateUrl: './modal.component.html',
styleUrls: [ './modal.component.css' ]
})
export class ModalComponent implements OnInit, OnDestroy {
@Input() id: string;
private element: any;
constructor(private modalService: ModalService, private el: ElementRef, private renderer: Renderer2) {
this.element = el.nativeElement;
}
ngOnInit(): void {
let modal = this;
if (!this.id)
return;
document.body.appendChild(this.element);
this.modalService.add(this);
}
ngOnDestroy(): void {
this.modalService.remove(this.id);
this.element.remove();
}
public open(): void {
this.element.style.display = 'block';
this.renderer.addClass(document.body, 'modal');
}
public close(): void {
this.element.style.display = 'none';
this.renderer.addClass(document.body, 'modal');
}
}
使用以下HTML模板:
<div class="modal">
<ng-content></ng-content>
</div>
<div class="overlay"></div>
然后是模式服务:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ModalService {
private modals: any[] = [];
add(modal: any) {
this.modals.push(modal);
}
remove(id: string) {
this.modals = this.modals.filter(x => x.id !== id);
}
open(id: string) {
let modal: any = this.modals.filter(x => x.id === id)[0];
modal.open();
}
close(id: string) {
let modal: any = this.modals.filter(x => x.id === id)[0];
modal.close();
}
}
我正在如下使用它:
<button (click)="modalService.open('modal-1')">Open Modal 1</button>
<modal id="modal-1">
<p>Modal 1</p>
<button (click)="modalService.close('modal-1');">Close Modal 1</button>
</modal>
启动时,模态默认是打开的,而不是关闭的。
有人知道我想念什么吗?
答案 0 :(得分:-1)
您直接在加载时看到了模式,因为您将modal
组件放入了DOM中,并且其display
的css属性最初并未设置为none
。
将display: none
设置为模式时,可以将其直接插入ModalService
的DOM中(最好将display
css属性的操作都放在同一位置)。
更新后的StackBlitz示例:https://stackblitz.com/edit/mk-angular-modal-tqpjbf
ngOnInit(): void {
let modal = this;
if (!this.id)
return;
this.element.style.display = 'none'; // set display: none when inserting modal in the DOM
document.body.appendChild(this.element);
this.modalService.add(this);
}