问题描述
我在页面上有多个自动完成功能,并且能够选择值并保存它们.我需要的是下次加载该页面时,默认情况下应为已选择并保存的值显示预先选择的值.
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}]
然后,您需要设置值
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
Please check this for reference https://stackblitz.com/edit/angular-8r153h-kpwhaa?file=app/autocomplete-display-example.ts
这篇关于如何设置垫自动完成的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!