I created a Angular
project where user can give inputs and validate forms as follows:
<form [formGroup]="angForm" novalidate>
<div class="form-group">
<label>Name:</label>
<input class="form-control" [(ngModel)]="name" formControlName="name" type="text" />
</div>
<div *ngIf="angForm.controls['name'].invalid && (angForm.controls['name'].dirty || angForm.controls['name'].touched)" class="alert alert-danger">
<div *ngIf="angForm.controls['name'].errors.required">
Name is required.
</div>
</div>
<div class="form-group">
<label>Address:</label>
<input class="form-control" [(ngModel)]="address" formControlName="address" type="text" />
</div>
<div *ngIf="angForm.controls['address'].invalid && (angForm.controls['address'].dirty || angForm.controls['address'].touched)" class="alert alert-danger">
<div *ngIf="angForm.controls['address'].errors.required">
email is required.
</div>
</div>
<button type="submit" (click)="buttonClicked()" class="btn btn-success">
Save
</button>
</form>
So as this is a reactive form, I tried to retrieve the values from the inputs as follows, assigned ngModel property in the text fields:
<input class="form-control" [(ngModel)]="name" formControlName="name" type="text" />
In the TypeScript
, I am doing something as follows:
export class SampleComponent implements OnInit {
constructor(private fb: FormBuilder) {
this.validateForm();
}
ngOnInit() {
}
angForm: FormGroup;
name: string;
address: string;
//Retrieve value from input field on button click
buttonClicked() {
alert("Button works with the value: " + this.name);
}
}
This works cool and I am getting the result as expected. But I've a model that has lot of properties. Say as an example:
export class SampleClass {
name: string;
address: string;
................
With other lot of fields
}
So my question is can I do something like this if I've the same model properties in the ngModel defined in the frontend, so is it valid or could be possible to define as follows:
this.SampleClass = this.angForm.value; //So all properties can be retrieved in one go
Right now, what I am doing is binding all properties one by one as follows:
obj: SampleClass ;
this.obj = new SampleClass();
this.obj.name= this.name;
this.obj.address= this.address;
If you use the reactive form, which means you shouldn't use ngmodel you can retrive form's value using getRawValue() method.