我正在尝试使用角形材料自动完成字段类型。我希望过滤器在我键入时工作。由于某种原因,我无法使其工作。我尝试将**[formControl]="myControl"**添加到输入属性,但随后收到另一个错误(ExpressionChangedAfterItHasBeenCheckedError)。
你能帮帮我吗?
我的组件HTML:
<div class="grid-container">
<mat-form-field appearance="outline">
<mat-label>{{label}}</mat-label>
<input matInput
placeholder="{{placeholder}}"
[(ngModel)]="inputValue"
[matAutocomplete]="auto"
#inputField="ngModel"
(ngModelChange)="onChange(inputValue)"
required>
<button mat-icon-button matSuffix (click)="writeValue('')">
<mat-icon>close</mat-icon>
</button>
<mat-autocomplete #auto="matAutocomplete">
<mat-option *ngFor="let option of filteredOptions | async" [value]="option">
{{option}}
</mat-option>
</mat-autocomplete>
<mat-error *ngIf="inputField.invalid || (inputField.dirty || inputField.touched)">
{{getErrorMessage()}}
</mat-error>
</mat-form-field>
<button mat-icon-button (click)="createNew()">
<mat-icon>add</mat-icon>
</button>
</div>
这是组件的TS文件:
import { ControlValueAccessor, FormControl, NG_VALUE_ACCESSOR } from '@angular/forms';
import { map, Observable, startWith } from "rxjs";
@Component({
selector: 'app-action-input-field',
templateUrl: './action-input-field.component.html',
styleUrls: ['./action-input-field.component.css'],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => ActionInputFieldComponent),
multi: true
}
]
})
export class ActionInputFieldComponent implements OnInit, ControlValueAccessor {
// input parameters for label and placeholder of field
@Input() label: string | undefined;
@Input() placeholder: string | undefined;
@Input() myControl: FormControl = new FormControl();
options: string[] = ['One', 'Two', 'Three'];
inputValue: string = '';
values: string[] = [];
selectedValue: string = '';
constructor() { }
filteredOptions: Observable<string[]> | undefined;
ngOnInit() {
this.filteredOptions = this.myControl.valueChanges.pipe(
startWith(''),
map(value => this._filter(value || '')),
);
}
public _filter(value: string): string[] {
const filterValue = value.toLowerCase();
return this.options.filter(option => option.toLowerCase().includes(filterValue));
}
writeValue(value: any): void {
this.inputValue = value;
}
registerOnChange(fn: any): void {
this.onChange = fn;
}
registerOnTouched(fn: any): void {
this.onTouched = fn;
}
getErrorMessage() {
return 'Toto pole je povinné';
}
onChange = (value: any) => {
this.inputValue = value
};
onTouched = () => { };
createNew() {
alert('create new');
}
}
2条答案
按热度按时间9lowa7mx1#
更新onChange方法以更新filteredOptions,这应该会更新筛选的选项
pb3s4cty2#
所以,问题出在@Input()上,我传递了FormControl,但没有将它与另一个组件绑定。
这个问题的解决方案是添加这种参数作为Input:
然后通过以下方式从中获取特定的FormControl:
我还将在form的.get()方法中为文本实现另一个Input参数。