We can add another instance of type to FormGroup
the form a nested form:
Explicitly calling new each time to create FormGroup
and FormControl
instance is cumbersome. Actually we can use FormBuilder
the factory pattern to create.
profileForm = this.fb.group({
firstName: ['Jerry'],
lastName: ['LastName'],
address: this.fb.group({
street: [''],
city: ['']
}),
});
Effect:
The parameter type after the colon is a JSON array, the first parameter is the default initial value, and the second parameter is the validator. The usage example is as follows:
When there is lastName
no maintenance value, the entire form is in the ng-invalid
state and the submit button cannot be clicked.
The status of nested groups will bubble up to the parent form.
Its status can be accessed directly through FormGroup.status.
this.profileForm.valueChanges.subscribe(
value => {
console.log('group value: ', value, ' status: ',
this.profileForm.status);
}
);
If we don't know the exact number of form control instances to create in advance, using dynamic controls is a good choice. The so-called dynamic controls, that is, we do not need to explicitly specify the key for each control.
A practical example:
aliases: this.fb.array([
this.fb.control('')
])
Create a getter accessor to get the dynamic control created above through code:
get aliases() {
return this.profileForm.get('aliases') as FormArray;
}
Because the type of the this.profileForm.get('aliases')
returned control is an abstract data type
AbstractControl
, you provide the method with an explicit type declaration to access the FormArray-specific syntax.
The way to dynamically add 匿名组件
:
addAlias() {
this.aliases.push(this.fb.control(''));
}
<div formArrayName="aliases">
<h2>Aliases</h2>
<button (click)="addAlias()" type="button">+ Add another alias</button>
<div *ngFor="let alias of aliases.controls; let i=index">
<!-- The repeated alias template -->
<label for="alias-{
{ i }}">Alias:</label>
<input id="alias-{
{ i }}" type="text" [formControlName]="i">
</div>
</div>
The final effect:
The values of these anonymous controls are printed out as follows:
onSubmit(){
console.warn(this.profileForm.value);
}
Index values are assigned to these anonymous controls via formArrayName
and formControlName
, so that the content in the controls can be accessed by index: