Angular 6 - 如何重构这些控件的代码

Angular 6 - How can I refactor the code for these controls

我有一个应用程序广泛使用了 Angular Material 自动完成控件。我们正在使用它们来允许用户 select 可以附加到表单的电子邮件地址。下面是我们如何使用它们

<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 = '';
   }

它工作正常,但我们在一个页面上有四个用于不同类型的电子邮件(抄送、密件抄送等),它们都以相同的方式工作,唯一的区别是对自动完成控件和电子邮件被推送到 selected 后的数组。我试图找到一种方法来重构 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 = '';

}

您只需将这两个属性作为附加参数传递给您的方法:

(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 = '';
}