I am aware of creating custom controls as components, but I can't figure out how to create custom groups.
The same we can do this by implementing ControlValueAccessor
and using a custom component like <my-cmp formControlName="foo"></my-cmp>
, how can we achieve this effect for a group?
<my-cmp formGroupName="aGroup"></my-cmp>
Two very common use-cases would be (a) separting a long form into steps, each step in a separate component and (b) encapsulating a group of fields which appear across multiple forms, such as address (group of country, state, city, address, building number) or date of birth (year, month, date).
Example usage (not actual working code)
Parent has the following form built with FormBuilder
:
// parent model
form = this.fb.group({
username: '',
fullName: '',
password: '',
address: this.fb.group({
country: '',
state: '',
city: '',
street: '',
building: '',
})
})
Parent template (inaccessible and non-semantic for brevity):
<!-- parent template -->
<form [groupName]="form">
<input formControlName="username">
<input formControlName="fullName">
<input formControlName="password">
<address-form-group formGroup="address"></address-form-group>
</form>
Now this AddressFormGroupComponent
knows how to handle a group which has these specific controls inside of it.
<!-- child template -->
<input formControlName="country">
<input formControlName="state">
<input formControlName="city">
<input formControlName="street">
<input formControlName="building">
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…