我已经在我的代码中实现了mat-autocomplete(在link中实现了),并且它运行良好,没有任何问题。
但是我需要将[formcontrol]更改为formcontrolname,以便将输入框与从DB填充的值绑定,并在保存时保存回DB。
当我使用formcontrolname时,除搜索/过滤值外,其他所有功能均正常运行。有人可以帮我解决使用formcontrolname时的搜索/过滤器问题。
答案 0 :(得分:0)
我想您的问题是您试图在创建表单之前订阅valueChanges,之后需要进行创建。例如
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))
);
}
答案 1 :(得分:0)
我制作了一个用于自动完成的组件,可以在项目中的任何地方使用它。 autocomplete.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
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;
}
}
现在您可以在任何组件中使用自动完成功能:
<app-autocomplete (onChange)="getFilterOptions($event,'Numbers')" formControlName="Numbers" [options]="options" [label]=" 'Select'" ngDefaultControl>
</app-autocomplete>
和component.ts:
getFilterOptions(options, controlName) {
this.myForm.get(controlName).reset(options);
}