I'm working on ControlValueAccessor
implementation in a child form. I have a parent form group and control as following
this.form = this.formBuilder.group({
user: ['', Validators.required]
});
<form [formGroup]="form">
<app-custom-input formControlName="user"></app-custom-input>
{{ form.get('user').value | json }}
</form>
And the child form
export class CustomInputComponent implements OnInit, ControlValueAccessor {
userInfo: FormGroup;
onChange = (value) => {};
onTouched = (value) => {};
constructor(private formBuilder: FormBuilder) { }
ngOnInit(): void {
this.userInfo = this.formBuilder.group({
fullName: ['', Validators.required],
email: ['', Validators.required]
});
}
writeValue(value): void {
console.log(value)
value && this.userInfo.setValue(value, {emitEvent: false});
}
registerOnChange(fn: any): void {
console.log("on change");
this.userInfo.valueChanges.subscribe(fn);
}
registerOnTouched(fn: any): void {
console.log("on touched");
this.onTouched = fn;
}
}
<ng-container [formGroup]="userInfo">
<label>Full name</label>
<input forControlName="fullName" type="text" name="fullName" />
<label>Email</label>
<input formControlName="email" type="email" />
</ng-container>
The value can be displayed just for the email
form control and updated on its change, but the fullName
sill the same during typing.
Its should be 'formControlName' instead of
<input forControlName="fullName" type="text" name="fullName" />