我对Angular 8有一个小问题-我不知道如何使用相同的方法显示具有各种内容的弹出窗口。我有两个组件-第一个组件包含带有一些信息链接的表单。
form-component.html
<a href="" (click)="openInfoPopup()">Info</a>
...
<a href="" (click)="openInfoPopup()">Info</a>
...
<a href="" (click)="openInfoPopup()">Info</a>
form-component.ts
openInfoPopup() {
...
let dialogRef = dialog.open(MyDialogComponent, dialogConf)
}
效果很好-openInfoPopup()可以根据需要打开我的对话框,但是到目前为止,我对Angular的了解不足,不允许我进行下一步。根据您单击的链接,我的弹出窗口应包含另一条短信。单击第一个链接应打开一个新对话框,其中包含下面数组的第一个元素等。在第二个组件中,我创建了一个包含消息的数组:
my-dialog-component.ts
infoArr = ["Text1", "Text2", "Text3", "Text4", "Text5", "Text6"];
my-dialog-component.html
<p *ngFor="let message of infoArr; let i = index"> {{ }} </p>
我应该怎么做才能使其正常工作?如何将数据从数组传输到form-component以及需要插入my-dialog-component.html插值中的内容?
这里要做的第一件事是参数化您的openInfoPopup()
调用。参数可以是不同类型的唯一键。为了简单起见,我将使用字符串。
form-component.html
<a href="" (click)="openInfoPopup('type1')">Info</a>
...
<a href="" (click)="openInfoPopup('type2')">Info</a>
...
<a href="" (click)="openInfoPopup('type3')">Info</a>
form-component.ts
openInfoPopup(type: string): void {
}
一旦知道事件的源头,您就可以将这些信息传递给任何决定相关内容是什么的人。它可能是弹出控件本身,或者您可以从其他位置注入内容。为了简单起见,我假设是由对话框来做出决定。
然后,我建议您更改对话框的方式。我不确定dialog.open(MyDialogComponent, dialogConf)
中发生了什么,但是它看起来不像在Angular中更新DOM的标准方式。您能解释一下这是怎么回事吗?
我将在父html中定义对话框组件。这不仅是声明父子关系的更标准方法,而且还为您将内容注入对话框组件提供了灵活性。
form-component.html(再次)
<dialog *ngIf="type" [type]="activeType" (close)="onDialogClose()">
</dialog>
form-component.ts
selectedType: string;
openInfoPopup(type: string): void {
this.selectedType = type;
}
onDialogClose(): void {
this.selectedType = null;
}
我对这里发生的事情有些猜测,但是如果我正确理解了您的问题,这可能就是我会遵循的模式。
一旦在窗体组件html中声明了对话框,则可以选择通过投影而不是@Input
属性来注入内容。它可能看起来像这样:
<dialog *ngIf="selectedType">
<div *ngIf="selectedType === 'type1'>
Something about type 1
</div>
<div *ngIf="selectedType === 'type2'>
Something about type 2
</div>
</dialog>