[英]Angular custom component FormControl pass value
I created a custom component for have autocomplete, now I would like to receive the value with FormControl but i can't get the value.我创建了一个具有自动完成功能的自定义组件,现在我想使用 FormControl 接收值,但我无法获取该值。
I call the custom component with the selector:我用选择器调用自定义组件:
<app-autocomplete-dropdown formControlName="example" [list]="profiloList"></app-autocomplete-dropdown>
But if i try to access to this.form.controls['example'].value
I don't get the value.但是,如果我尝试访问this.form.controls['example'].value
我没有得到值。
public inizialize(): void {
this.form = this.formBuilder.group({
example: [null]
});
}
Custom Component TS File :自定义组件 TS 文件:
export class AutocompleteDropdownComponent implements ControlValueAccessor {
@Input()
list: Array<any> = [];
selectedElement!: Object;
selectedTitle?: String;
onChange: any = () => { }
onTouch: any = () => { }
touched = false;
disabled = false;
constructor() {
}
changes(event: Event) {
if (this.disabled) return
this.markAsTouched()
this.selectedElement = event?.target ? (event?.target as HTMLTextAreaElement).value : ''
this.onChange(this.selectedElement)
}
writeValue(obj: any): void {
this.selectedElement = obj;
}
registerOnChange(fn: any): void {
this.onChange = fn;
}
registerOnTouched(fn: any): void {
this.onTouch = fn;
}
setDisabledState?(isDisabled: boolean): void {
this.disabled = isDisabled;
}
markAsTouched() {
if (!this.touched) {
this.onTouch();
this.touched = true;
}
}
}
Custom Component HTML File :自定义组件 HTML 文件:
<input type="text" class="input" list="list" (keyup)="changes($event)">
<i class="bz-chevron-down icon arrow"></i>
<datalist id="list">
<option *ngFor="let element of list" [value]="element.objectTitle">
{{element.objectTitle}}</option>
</datalist>
There are no problems in the code in the question, I do not see the metadata for the AutocompleteDropdownComponent, assuming the problem might be in the metadata问题中的代码没有问题,我没有看到 AutocompleteDropdownComponent 的元数据,假设问题可能出在元数据中
This is how the meta data for the component should look like组件的元数据应该是这样的
@Component({
selector: 'app-autocomplete-dropdown',
templateUrl: './autocomplete-dropdown.component.html',
styleUrls: ['./autocomplete-dropdown.component.css'],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => AutocompleteDropdownComponent),
multi: true,
},
],
})
export class AutocompleteDropdownComponent implements ControlValueAccessor {
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.