Reactive Forms
The Form object will be programmatically created by angular and the entire FORM object will be synchronized with DOM.
Before sending data any manipulation needs to be done then prefer to use the Reactive form.
<div class="container">
<form [formGroup]="loginForm">
Name: <input type="text" class="form-control" formControlName="name"/>
Password: <input type="text" class="form-control" formControlName="password"/>
<div class="text-danger" *ngIf="loginForm.controls['password'].touched">
<span *ngIf="loginForm.controls['password'].errors?.['required']">This is Required</span>
<span *ngIf="loginForm.controls['password'].errors?.['minlength']">3 Charecter Required</span>
</div>
<button class="btn btn-success" [disabled]="loginForm.invalid" (click)="onSave()">Submit</button>
</form>
</div>
Value is: {{objs|json}}
Ex.ts:
//imports: [ReactiveFormsModule,JsonPipe,CommonModule],
export class PraticeComponent {
objs: any;
loginForm:FormGroup = new FormGroup({
name: new FormControl(''),
password: new FormControl('',[Validators.required,Validators.minLength(3)])
});
onSave(){
this.objs = this.loginForm.value
}
}
//imports: [ReactiveFormsModule,JsonPipe,CommonModule],
export class PraticeComponent {
//Form Builder Approach
objs: any;
loginForm!: FormGroup;
constructor(private fb: FormBuilder) {
this.loginForm=this.fb.group({
name: new FormControl(''),
password: new FormControl('',[Validators.required,Validators.minLength(3)])
});
}
onSave(){
this.objs = this.loginForm.value
}
}
Comments
Post a Comment