我有一个自定义组件,该组件实现ControlValueAccessor并正确响应父组件FormGroup中的更新,并在更新UI时更新该FormGroup。
现有的应用程序模板就是这样
<form-input
inputType="radio"
id="method-del"
formControlName="method"
inputValue="Delivery"
><label>Delivery</label>
</form-input>
和表单输入:
@Component({
selector: 'form-input',
template: `<input #input
type="{{ inputType }}"
id="{{ id || formControlName }}"
[value]="inputValue"
(blur)="onBlur($event)"
(keyup)="onKeyup(input.value)"
(focus)="onFocus(input.value)"
(change)="onChange($event)"
/>`,
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => InputComponent),
multi: true,
},
],
})
export class InputComponent implements ControlValueAccessor, OnInit {
...
registerOnChange(fn: any): void {
this.onChangeCallback = fn;
}
registerOnTouched(fn: any): void {
this.onTouchedCallback = fn;
}
writeValue(value: any): void {
this.checked = value === this.inputValue;
}
}
但是我现在需要将自定义组件包装在另一个自定义组件中,我不知道应该怎么做。包装自定义组件现在是否还需要实现ControlValueAccessor?如果是这样,应该如何将嵌套自定义组件中的onChangeCallback连接到包装自定义组件中的onChangeCallback?并且两个组件都应具有NG_VALUE_ACCESSOR的提供程序,以将引用转发给自己吗?还是有一种理想的方法来使包装组件只是传递?
-App (<form [formGroup=""]>
|
- WrappingInputComponent <-------This needs to be inserted in the chain
|
- FormInputComponent
|
- <input/>
使用[formControl]将formControl传递给包装组件>
//wrappingInputComponent @Input(control) control; <form-input inputType="radio" id="method-del" [formControl]="control" inputValue="Delivery"> <label>Delivery</label> </form-input>
和您的应用程序组件
//App component
<form [formGroup]="form">
<wrapping-component [control]="form.get('method')"><wrapping-component>
</form>