我有一个可以广泛使用Angular Material自动完成控件的应用程序。我们使用它们来允许用户选择可以附加到表单的电子邮件地址。这是我们使用它们的方式
<mat-form-field class="input-width-500">
<mat-chip-list #recipientChipList>
<mat-chip *ngFor="let email of emailRecipients"
(removed)="removeEmailList(email)">{email}}
<mat-icon matChipRemove>cancel</mat-icon>
</mat-chip>
<input type="text" matInput placeholder="Add Recipients"
formControlName="addRecipient"
[matAutocomplete]="autoRecipient"
[matChipInputFor]="recipientChipList"
(matChipInputTokenEnd)="addEmail($event)">
</mat-chip-list>
<mat-autocomplete #autoRecipient="matAutocomplete"
[displayWith]="displayEmailIds"
(optionSelected)="addEmailList($event)">
<mat-option *ngFor="let val of filteredRecipients" [value]="val">
{{val}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
以及用于添加电子邮件的后端代码:
addEmail(event: MatChipInputEvent): void {
const input = event.input;
const value = event.value;
if (!this.autoRecipient.isOpen) {
if (input && value !== '') {
this.emailRecipients.push(value);
input.value = '';
}
}
input.value = '';
}
它工作正常,但是我们在一个页面上有四个,分别用于不同类型的电子邮件(抄送,密件抄送等),它们都以相同的方式工作,唯一的区别是对自动完成控件和数组的引用电子邮件一旦被选中就被推送到。我试图找到一种重构addEmail函数的方法,以便我们只有一个函数,但是到目前为止,我似乎过于复杂了。在此寻找一些一般方向,请先谢谢。
编辑:
因此我已将其添加到模板中:
(matChipInputTokenEnd)="newAddEmail($event, autoRecipient, addRecipientCtrl, emailRecipients)"
,然后到后端:
newAddEmail(event: MatChipInputEvent, autoControl: MatAutocomplete, recipientControl: AbstractControl, emailArray: any[]): void {
const input = event.input;
const value = event.value;
if (!autoControl.isOpen) {
if (input && value !== '') {
emailArray.push(value);
input.value = '';
}
}
input.value = '';
}
答案 0 :(得分:1)
您只需要将两个属性作为附加参数传递给您的方法:
(optionSelected)="addEmailList($event, autoRecipient, emailRecipients)">
[...]
addEmail(event: MatChipInputEvent, autoComplete: MatAutoComplete, recipients: Array<Something>) {
const input = event.input;
const value = event.value;
if (!autoComplete.isOpen) {
if (input && value !== '') {
recipients.push(value);
input.value = '';
}
}
input.value = '';
}