Reputation: 75
Here I'm having simple form as
<form [formGroup]="loginform">
<input type="text" formControlName="EmailId"/>
<input type="text" formControlName="password"/>
<button [disabled]="!loginform.valid" (click)="ValidateUser()"></button>
<form>
My Ts code as loginform!:FormGroup; Here im mentioned my validation as
ngOnInit(): void {
this.loginform=this.fb.group({
EmailId:['',[Validators.required]],
password:['',[Validators.required]
})
}
Geing values as
get f(): { [key: string]: AbstractControl } {
return this.loginform.controls;
}
Here is my Interface
export interface logindetails{
EmailId:string;
password:string;
}
on my submission
ValidateUser(objuser:logindetails){
}
from my HTML to here how can I bind values to my interface?
Upvotes: 1
Views: 1825
Reputation: 783
Im assuming you want strongly typed reactive form
Declaring the interfaces
interface ILoginForm {
EmailId: string;
password: string;
}
// Interface IUserFormGroup extends FormGroup {
loginForm: ILoginForm;
// We need to add these manually again, same fields as ILoginForm
controls: {
EmailId: AbstractControl;
password: AbstractControl;
};
}
Initializing the formbuilder group
form: ILoginForm;
constructor(private formBuilder: FormBuilder) {
// initialize the form
this.form = this.formBuilder.group({
EmailId:['',[Validators.required]],
password:['',[Validators.required]
}) as ILoginForm; // make sure to double-check this list with the interface
}
const loginData: ILoginForm = this.form.value; // this is now valid typescript
ValidateUser(){
const loginData: ILoginForm = this.form.value; // this is now valid typescript
console.log(`Login data ${loginData.EmailId}`);
}
More advanced and generic solution Angular strongly typed reactive forms
Upvotes: 0
Reputation: 379
You can simply add these on your .ts
file:
onEmailIdChanged(event:any){
this.EmailId = event.target.value;
}
onPasswordChanged(event:any){
this.password = event.target.value;
}
and on your .HTML
do this:
<input type="text" formControlName="EmailId" (change)="onEmailIdChanged($event)/>
<input type="text" formControlName="password" (change)="onPasswordChanged($event)/>
Upvotes: 1