好吧,如果您想“重新发明轮子”,请不要忘记在单击外部时关闭模态
改进 Luixaviles 的答案,组件模式可以像
<div #myModal class="container" (click)="tryClose()">
<div #content class="content">
<ng-content></ng-content>
</div>
</div>
好吧,你看到我做了一个函数“tryClose”,如果你点击 div “myModal”,这个函数检查我们是否点击,但我们没有点击里面的“内容”
tryClose() {
const clickTarget = event.target as HTMLElement;
if (!(this.content.nativeElement as HTMLElement).contains(clickTarget))
this.close();
}
使用<ng-content>允许我们在 app.component 中写一些类似
<app-modal #modal>
<p>Some content here...</p>
<button (click)="modal.close()">Close</button>
</app-modal>
<p>
Open a Pure HTML + CSS with Angular
</p>
<button (click)="modal.open()">Open Modal</button>
模态组件中的其余代码很简单:
export class ModalComponent {
@ViewChild("myModal", { static: false }) modal: ElementRef;
@ViewChild("content", { static: false }) content: ElementRef;
open() {
this.modal.nativeElement.style.display = "block";
}
close() {
this.modal.nativeElement.style.display = "none";
}
}
查看Luixaviles 的分叉堆栈闪电战
更新一个简单的 stopPropagation 让思考更轻松
<div #myModal class="container" (click)="close()">
<div (click)="$event.stopPropagation()" class="content">
<ng-content></ng-content>
</div>
</div>