我正在将表单输入数据保存到NGRX存储中。我想稍后将保存的数据绑定回表单。
所以我有一个如下的反应形式。
<form [formGroup]="searchForm" id="searchForm" style="width:100%;height:70%" (ngSubmit)="onSubmit()">
<mat-form-field>
<input type="text" placeholder="Direction" aria-label="Assignee" formControlName="direction" matInput [matAutocomplete]="autoDirection">
<mat-autocomplete #autoDirection="matAutocomplete" placeholder="Direction" [displayWith]="displayFn">
<mat-option *ngFor="let directions of filteredDirectionList | async " [value]="directions">{{directions.name}}</mat-option>
</mat-autocomplete>
</mat-form-field>
</form>
下面是TS文件
searchForm: FormGroup;
export const directionList: Array<any> = [{ name: 'Out', value: '1' }, { name: 'In', value: '2' } ];
ngOnInit(){
this.searchForm = this.formBuilder.group({
direction: [null, Validators.compose([Validators.nullValidator, this.valueSelected(this.directionList)])],
});
this.filteredDirectionList = of(this.directionList);
}
valueSelected(myArray: any[]): ValidatorFn {
return (c: AbstractControl): { [key: string]: boolean } | null => {
if (c && c.value && c.value !== '') {
const selectboxValue = c.value;
const pickedOrNot = myArray.filter(alias =>
alias.name === selectboxValue.name);
if (pickedOrNot.length > 0) {
// everything's fine. return no error. therefore it's null.
return null;
} else {
// there's no matching selectboxvalue selected. so return match error.
return { 'match': true };
}
}
}
}
displayFn(field?: any): string | undefined {
console.log(field ? field.name : undefined) // show undefined
return field ? field.name : undefined;;
}
所以上面的代码是显示过滤后的垫子自动完成功能的基本结构
我的意图是
我想传递一个对象以将该对象绑定到字段,以便它将在加载时显示它。 我尝试了以下方法
// approach 1
this.searchForm.controls['direction'].setValue(this.directionList.find(obj => { return obj.value === "Out"}));
//approach 2
this.searchForm.value.direction = {name: "Out", value: "1"};
我的预期输出如下:
但是我只是得到一个没有绑定的空白字段。