[英]Angular mat-autocomplete not filtering values when i use formcontrolname instead [formcontrol]
I have implemented mat-autocomplete in my code (as implemented in the link ) and it works perfectly well without any issues.我已经在我的代码中实现了 mat-autocomplete(如在链接中实现的那样),它运行良好,没有任何问题。
But I need to change [formcontrol] to formcontrolname so that input box will be binded with values populated from DB and saved back to DB while saving.但我需要将 [formcontrol] 更改为 formcontrolname,以便输入框与从 DB 填充的值绑定,并在保存时保存回 DB。
When i use formcontrolname, everything works well, except the search/filtering values.当我使用 formcontrolname 时,一切正常,除了搜索/过滤值。 Could some one help me in fixing the search/filter issues while using formcontrolname.
有人可以帮助我在使用 formcontrolname 时解决搜索/过滤问题吗?
I suppose your problem is that you're trying to subscribe to valueChanges before create the form, you need make it after.我想您的问题是您在创建表单之前尝试订阅 valueChanges,您需要在之后进行。 eg
例如
ngOnInit() {
//create the form
this.myForm=new FormGroup({
control:new FormControl()
})
//after subscribe to valueChanges
this.filteredOptions = this.myForm.get('control').valueChanges
.pipe(
startWith(''),
map(value => this._filter(value))
);
}
I have made a component for autocomplete and use it wherever in my project.我已经制作了一个用于自动完成的组件,并在我的项目中的任何地方使用它。 autocomplete.component.html:
自动完成.component.html:
<mat-form-field class="example-full-width">
<mat-label> {{label}}</mat-label>
<input type="text" aria-label="Number" matInput [matAutocomplete]="auto"
[formControl]="myControl">
<mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
<mat-option *ngFor="let option of filteredOptions | async" [value]="option">
{{option.Text}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
autocomplete.component.ts自动完成组件.ts
export class AutocompleteComponent implements OnInit {
filteredOptions: Observable<SelectedListItem[]>;
@Output() public onChange: EventEmitter<any> = new EventEmitter();
@Input() public label: string = "Select";
@Input() public options: any[];
@Input() public mycontrol: FormControl;
myControl = new FormControl();
constructor() { }
ngOnInit() {
this.filteredOptions = this.myControl.valueChanges
.pipe(
startWith(''),
map(value => {
if (value.length > 2) {
return this._filter(value);
} else {
return null;
}
})
);
}
displayFn(item: SelectedListItem) {
try { return item.Text; }
catch{ }
}
private _filter(value: string): any[] {
var result = this.options.filter(option =>
option.Text.toLowerCase().includes(value.toLowerCase()));
this.onChange.emit(result);
return result;
}
}
Now you can use autocomplete in any component:现在您可以在任何组件中使用自动完成功能:
<app-autocomplete (onChange)="getFilterOptions($event,'Numbers')" formControlName="Numbers" [options]="options" [label]=" 'Select'" ngDefaultControl>
</app-autocomplete>
and component.ts:和component.ts:
getFilterOptions(options, controlName) {
this.myForm.get(controlName).reset(options);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.