Template Based form
For this you need to import FormsModule. As soon as you import FormsModule, ngForm directive becomes active on all <form> tags. You can export it into a local template variable (#myForm="ngForm"). This will give access to aggregate form value (myForm.value), child controls (myForm.controls['control's name attribute']) and validity status (myForm.controls['formElement'].valid or myForm.valid) as well as user interaction properties like dirty (myForm.controls['formElement'].dirty), touched(myForm.controls['formElement'].touched) etc.
Angular provides ngSubmit ((ngSubmit)="saveMe(myForm.value)") directive which prevents form to be submitted to server
For binding you can use ngModel. If you need two way binding then use [()]. () Html to component direction, [] component to html
[(ngModel)]="somePropertyDefinedInComponent" ngModel require name attribute
In theory you should be able to use input event and then assign any of the component's property to the value of the input element. Most likely you will not do this as angular provides shot cut methods as described earlier.
(input)="somePropertyDefinedInComponent=$event.target.value"
ngModelGroup - If you want to group certain properties nested within property then you use ngModelGroup="property under which all elements will be nested"
Model based form or reactive form
In template based approach all the logic resides in html, so complex scenarios (like cross field validation etc.) may not be easy to achieve and also you cannot unit test your code. So for this case you can use reactive form for which you need to import ReactiveFormsModule. In your component you create FormGroup and add all form controls to it
myFormGroup = new FormGroup({
name: new FormControl('', [Validators.required, Validators.pattern('[a-zA-Z].*')]), address: new FormArray([ new FormGroup({ city: new FormControl(), state: new FormControl(), }) ]), cityVisited: new FormArray([ new FormControl() ]) })
In the template, bind form formGroup attribute to the FormGroup object created in the component and input elements you need to bind it the FormControl property of component
<form [formGroup]="myFormGroup"
formControlName="name" or [formControl]="myFormGroup.controls.name"
<div *ngFor="let item of myFormGroup.controls.address.controls; let i=index">
<input [formControl]="item.controls.state" />
</div>
<div *ngFor="let item of myFormGroup.controls.cityVisited.controls; let i=index">
<input [formControl]="item" />
</div>FormGroup tracks the value and validity state of a group of FormControl instances.
Custom Validation
Create a function which takes FormControl as a parameter and returns object (property usually with the validator name and value as any value which you may want to show). If the function returns null then its valid otherwise its invalid. You can also create directive and implements Validator. You can call updateValueAndValidity() on specific controller to trigger its validation.
No comments:
Post a Comment