如何设置垫自动完成的默认值

时间:2019-05-19 12:57:57

标签: angular angular-material mat-autocomplete

我在页面上有多个自动完成功能,并且能够选择值并保存它们。我需要的是下次加载该页面时,默认情况下应为已选择并保存的值显示预先选择的值。

以下是代码段-

<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上,我能够获取保存在地图中的值,并且正在使用以下无效的逻辑-

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)">

但是它不起作用。有什么建议可以实现吗?

enter image description here

1 个答案:

答案 0 :(得分:2)

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

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

然后,您需要设置值

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

如果设置类似,它将设置默认值

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

然后它将不起作用。

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

相关问题