【问题标题】:Angular mat-autocomplete with dynamic inputs具有动态输入的角垫自动完成
【发布时间】:2018-12-24 17:50:38
【问题描述】:

我是 Angular Material Design 的新手,我对动态输入的 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>

【问题讨论】:

  • 为什么要使用单个 mat-autocomplete?我知道这并不能回答这个问题,但更多的背景背景可能有助于给出答案。没有任何背景或原因,我建议您只为每个输入使用 mat-autocomplete。
  • @G.Tranter 很清楚他想要做什么。您需要设置一个 HTML-id(本例中为#auto)以便在材料的指令([matAutocomplete]="auto")中引用它。但据我所知,没有办法在模板中动态设置 id

标签: angular-material mat-autocomplete


【解决方案1】:

您必须使用多个自动完成元素,并且所有输入都需要与 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())
        );
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-19
    • 2020-03-28
    • 2013-04-09
    • 1970-01-01
    • 1970-01-01
    • 2018-10-10
    相关资源
    最近更新 更多