[英]How to build reusable field for reactive form in Angular
I am trying to build a reusable field component for reactive form but I am unable to get a value from custom-input
component.我正在尝试为反应式表单构建一个可重用的字段组件,但我无法从custom-input
组件中获取值。
<form [formGroup]="form" (ngSubmit)="submit()">
<custom-input id="name" name="name" formControlName="name"></custom-input>
<button type="submit" name="button">Submit</button>
</form>
My custom input reusable componeent我的自定义输入可重用组件
import { Component, OnInit, Input } from '@angular/core';
import { FormControl } from "@angular/forms";
@Component({
selector: 'custom-input',
template: '<input type="text" [class]="class" [id]="id" [name]="name" [formControlName]="formControlName">',
styles: []
})
export class CustomInputComponent implements OnInit {
@Input() public id: string;
@Input() public class: string;
@Input() public name: string;
@Input() public formControlName: string;
constructor() { }
ngOnInit() {
}
}
You can implement ControlValueAccessor
, but might not want to re-implement the methods for the native input.您可以实现ControlValueAccessor
,但可能不想重新实现本机输入的方法。 In order to do that, you can use the FormControlDirective
to get access to valueAccessor.为此,您可以使用FormControlDirective
来访问 valueAccessor。
formControl
and formControlName
are added as input properties, so it will work in both cases. formControl
和formControlName
被添加为输入属性,因此在这两种情况下都可以使用。 If formControlName
is provided, the instance of FormControl
will be retrieved from the ControlContainer
.如果提供了formControlName
,则FormControl
的实例将从ControlContainer
中检索。
@Component({
selector: 'app-custom-input',
template: `<input type="text" [formControl]="control">`,
styleUrls: ['./custom-input.component.scss'],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: CustomInputComponent,
multi: true
}
]
})
export class CustomInputComponent implements ControlValueAccessor {
@Input() formControl: FormControl;
@Input() formControlName: string;
@ViewChild(FormControlDirective, {static: true})
formControlDirective: FormControlDirective;
private value: string;
private disabled: boolean;
constructor(private controlContainer: ControlContainer) {
}
get control() {
return this.formControl || this.controlContainer.control.get(this.formControlName);
}
registerOnTouched(fn: any): void {
this.formControlDirective.valueAccessor.registerOnTouched(fn);
}
registerOnChange(fn: any): void {
this.formControlDirective.valueAccessor.registerOnChange(fn);
}
writeValue(obj: any): void {
this.formControlDirective.valueAccessor.writeValue(obj);
}
}
Source: https://medium.com/angular-in-depth/dont-reinvent-the-wheel-when-implementing-controlvalueaccessor-a0ed4ad0fafd资料来源: https://medium.com/angular-in-depth/dont-reinvent-the-wheel-when-implementing-controlvalueaccessor-a0ed4ad0fafd
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.