如何设置垫子自动完成的默认值 [英] How to set default values for mat autocomplete

查看:21
本文介绍了如何设置垫子自动完成的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个页面上有多个自动完成功能,可以选择值并保存它们.我需要的是,当我下次加载页面时,默认情况下应显示已选择并保存的值的预选值.

I have multiple auto complete on a page and able to select values and save them. What I need is when I load the page next time, the pre selected values should be displayed by default for the ones already selected and saved.

以下是代码片段-

<ng-container matColumnDef="course">
      <th mat-header-cell *matHeaderCellDef mat-sort-header> Course Section </th>
      <td mat-cell *matCellDef="let course"> {{course.courseSection}}
      <mat-form-field>
          <input type="text" id="{{course.courseSection}}" placeholder="Pick one" aria-label="Number" matInput [formControl]="myControl"
            [matAutocomplete]="auto">
          <mat-autocomplete #auto="matAutocomplete" (optionSelected)="onSelectionChanged(course.courseSection, $event)">
            <mat-option *ngFor="let option of filteredOptions | async" [value]="option">
              {{option}}
            </mat-option>
          </mat-autocomplete>
        </mat-form-field>
      </td>
    </ng-container>

在 ngOnInit 上,我能够获取保存在地图中的值,并且使用了以下不起作用的逻辑 -

On ngOnInit, I am able to get the values saved in a map and was using the below logic which doesn't work -

checkAssigned(section: string) {
    if (this.assigned.has(section)) {
      return this.assigned.get(section);
    } else {
      return '';
    }
} 

HTML -

<mat-option *ngFor="let option of filteredOptions | async" 
[value]="checkAssigned(course.courseSection)===''? option : checkAssigned(course.courseSection)">

但它不起作用.关于如何实现它的任何建议?

But it doesn't work. Any suggestions as how can I achieve it?

推荐答案

对于设置值,它应该类似于您在 matAutoComplete 列表中使用的格式.

For setting values, it should similar to the format that you're using in the matAutoComplete list.

假设您使用的是 myNameList = [{name:"My Name",id:1},{name:"My name 2",id:2}]

然后为此,您需要设置值

Then for that, you need to set the value

this.myformName.controls['myControl'].setValue({name: "My Name", id:1}); //Working Code

如果你像这样设置它会设置默认值

it will set the default value if you are setting like

this.myformName.controls['myControl'].setValue("My Name"); //Not working code

那就不行了.

请检查此以供参考 https://stackblitz.com/edit/angular-8r153h-kpwhaa?file=app/autocomplete-display-example.ts

这篇关于如何设置垫子自动完成的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆