我想你需要做的是让两个变量保持
listOfItems
和A
selectedItem
您将在模式中显示的位置。例如
组件TS文件
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit{
listOfItems: any[];
selectedItem: any;
ngOnInit() {
this.listOfItems = [
{
title: 'Title 1',
content: 'this is my first item'
},
{
title: 'Title 2',
content: 'this is my second item'
}
];
}
openModal( item ) {
this.selectedItem = item;
}
closeModal() {
this.selectedItem = undefined;
}
}
所以我们有
openModal
它在
选择项目
变量用于显示特定项并让模式显示,closemodal用于撤消值并使模式再次隐藏。所以在HTML上实现这个看起来是这样的。
组件HTML
<button *ngFor="let item of listOfItems; let i = index" (click)="openModal(item)" class="w3-button">Open item #{{ i }}</button>
<div *ngIf="selectedItem" class="w3-modal" [style.display]="selectedItem ? 'block' : 'none'">
<div class="w3-modal-content">
<div class="w3-container">
<span (click)="closeModal()" class="w3-button w3-display-topright">×</span>
<h1>{{ selectedItem.title }}</h1>
<p>{{ selectedItem.content }}</p>
</div>
</div>
</div>
所以我们有一个按钮,可以循环浏览项目列表并在函数上传递项目,这样我们就可以选择要显示的项目。然后在模态中,我们尝试检查
选择项目
已定义,因此如果是,则显示将可见,否则不可见。