Bonjour, Habr! Je présente à votre attention la traduction de l'article "Convertir en formes angulaires fortement typées en une minute" par Ajay Ojha.
Dans cet article, nous allons apprendre à transformer un formulaire réactif en un formulaire fortement typé sans changer la définition de classe.
TypeScript . , Angular . Angular . - «any», , ..
, Angular. , , . «», .
frontend- , . , , , , , - .
:
- ;
- valueChanges statusChanges FormControl ;
- FormGroup FormArray - .
(FormGroup, FormControl FormArray), . , :
- FormBuilder FormControl, FormGroup FormArray;
- ;
- , FormGroup , @angular/forms.
, .
? ?
, .
?
@rxweb/types. , , - .
, FormControl FormGroup FormArray. FormGroup.
export class AppComponent implements OnInit {
formGroup: FormGroup;
formBuilder: FormBuilder;
constructor(formBuilder: FormBuilder) {
this.formBuilder = formBuilder;
}
ngOnInit() {
this.formGroup = this.formBuilder.group({
firstName: ['', [Validators.required]],
address: this.formBuilder.group({
countryName: ["", Validators.required]
}),
skills: this.formBuilder.array([
this.formBuilder.group({
name: ["", Validators.required]
})
])
});
}
}
.
1.
npm install @rxweb/types
2.
. :
User >> firstName, address, skills; Address >> countryName; Skill >> name.
3.
:
- IFormGroup: API FormGroup;
- IFormBuilder: FormGroup, FormControl FormArray.
:
import { IFormGroup, IFormBuilder } from “@rxweb/types”;
4.
:
- FormGroup IFormGroup;
- FormBuilder IFormBuilder;
-
group<User>
,group<Address>
array<Skill>
.
, , .
:
formGroup: IformGroup<User>;
formBuilder: IformBuilder;
ngOnInit() {
this.formGroup = this.formBuilder.group<User>({
firstName: ['', [Validators.required]],
address: this.formBuilder.group<Address>({
countryName: ["", Validators.required]
}),
skills: this.formBuilder.array<Skill>([
this.formBuilder.group({
name: ["", Validators.required]
})
])
});
}
, .
/,
, , . , , , , , - , «New Way to Validate the Angular Reactive Form».