Angular 表单验证值分配给接口

Angular Form validation values asssign to interface

这里我有简单的形式

<form [formGroup]="loginform">
<input type="text" formControlName="EmailId"/>
<input type="text" formControlName="password"/>
<button [disabled]="!loginform.valid" (click)="ValidateUser()"></button>
<form>

我的Ts代码为 登录表单!:表单组; 在这里我提到我的验证为

ngOnInit(): void {
    this.loginform=this.fb.group({
      EmailId:['',[Validators.required]],
      password:['',[Validators.required]
    })
  }

Geing 值为

 get f(): { [key: string]: AbstractControl } {
    return this.loginform.controls;
  }

这是我的界面

export interface logindetails{
    EmailId:string;
    password:string;
}

根据我的意见

ValidateUser(objuser:logindetails){
} 

从我的 HTML 到这里如何将值绑定到我的界面?

我假设你想要强类型的反应形式

声明接口

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;
   };
}

正在初始化 formbuilder 组

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}`);
} 

更高级和通用的解决方案

您只需将这些添加到您的 .ts 文件中即可:

onEmailIdChanged(event:any){
    this.EmailId = event.target.value;

  }
  onPasswordChanged(event:any){
    this.password = event.target.value;
  }

并在您的 .HTML 上执行此操作:

<input type="text" formControlName="EmailId" (change)="onEmailIdChanged($event)/>
<input type="text" formControlName="password" (change)="onPasswordChanged($event)/>