2

我是角度材料设计的新手,我对动态输入的 mat-autocomplete 有疑问。By default user see one input but when some value is selected than another input can be added and this is the tricky part - how to make that all those inputs will be using only one mat-autocomplete? 可能吗?

下面是我使用 mat-autocomplete 的代码。addItem() 函数正在添加另一个输入,该输入将绑定到同一个 mat-autocomplete。它应该移到上面吗?那么唯一ID呢?如何通过连接到同一个 mat-autocomplete 的多个输入来解决这个问题?

<div formArrayName="items" class="form-group"
    *ngFor="let item of items.controls; let i = index">

    <mat-form-field class="example-full-width">
        <input required type="text" placeholder="Item ID"
            matInput
            [formControlName]="i"
            [id]="i"
            [matAutocomplete]="auto">

        <mat-autocomplete #auto="matAutocomplete">
            <mat-option *ngFor="let option of filteredOptions | async"
                [value]="option.code"
                (click)="selectOption(option, i)">
                {{option.code}}
            </mat-option>
        </mat-autocomplete>

    </mat-form-field>

    <i *ngIf="i == 0 && selected" class="fa fa-plus add-vessel"
        aria-hidden="true"
        (click)="addItem()"></i>

    <i *ngIf="i !== 0 && canRemove" class="fa fa-minus add-vessel"
        aria-hidden="true"
        (click)="removeItem(i)"></i>

</div>
4

1 回答 1

0

您必须使用多个自动完成元素,并且所有输入都需要与 valueChanges 事件捕获函数数组绑定。原因是如果您尝试将 valueChanges 与 formArray ("items") 绑定,那么该函数将执行数组中输入的次数。使用以下代码实现目标。

for(var i = 0;i<numberOfInputElements;i++){
    const items = this.form.get('items') as FormArray;
    this.filteredOptions[index] = items.at(index).get('item').valueChanges
        .pipe(
          startWith(''),
          map((value: string) => (value) ? this._filter(value, this.options) : this.options.slice())
        );
}
于 2019-06-20T17:13:07.713 回答