首页 > 解决方案 > 表单验证不适用于角度

问题描述

我有一个反应式表单,在填写 aa 输入之前,应该禁用提交按钮

我曾尝试使用 ngmodel 和 ngForm 参数来禁用按钮,但在填充输入时未启用

这是我的代码

<form #uploadForm="ngForm">
    <div class="uploadDiv">
  <div *ngFor="let data of fileList, let i = index">

    <label class="adpLabel">{{data.fileDesc}}</label>   
    <input readonly class="adpInput" type="text" [(ngModel)]='listFilter' name="listFilter" value={{filename[i]}}>
    <input type="file" id="{{data.fileName}}"
    #selectFiles hidden accept=".xls,.xlsx" (change)="getFileInfo($event, i)">
    <button mat-button (click)="selectFiles.click()" class="browseBtn">Browse</button>    
  </div>

<div class="adpButtons"> 
        <button mat-button [disabled]="!uploadForm.valid" (click)="clickFileUpload()">Upload</button>
        <button mat-button disableRipple tabindex="-1" mat-dialog-close>Back</button>
</div>

    </div>
</form>

我希望在填充输入时启用上传按钮

编辑 1:添加 ts 代码

getFileInfo(event, i) {
   if(this.file[i]){
      this.file.splice(i,1,event.target.files);
      this.fileType.splice(i,1,event.target.id);
   }
   else{
      this.file[i]=event.target.files;
      this.fileType[i]=event.target.id;
      //this.file.push(event.target.files);
      //this.fileType.push(event.target.id);
   }
   for (let j = 0; j < this.file.length; j++) {
      let fileName:string='';
      let extension:string;
      if(event.target.files[j]){
       fileName=event.target.files[j].name;
       extension = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
      } 
      let id:any; 
      if(this.fileType[j]){
        id=this.fileType[j];
      }
      if ( extension==".xls" || extension==".xlsx" ) {
        this.filename[i] = fileName; 
        this.fileType[i] = id;
      }
   }
}

标签: angularangular2-formsangular-reactive-formsangular2-ngmodel

解决方案


您并没有真正使用 Angular Reactive Forms - 或者至少没有正确使用。 https://angular.io/guide/reactive-forms

您在 .ts 文件中定义一个 Formgroup 和 Controls,在 .html 文件中定义一个带有控件的表单并连接两者。

https://stackblitz.com/edit/angular-reactive-forms?file=app%2Fapp.component.html

.ts

SignupForm: FormGroup;

this.SignupForm = new FormGroup({
 'username':new FormControl(null),
 'email':new FormControl(null)
});

.html

<form [formGroup]="SignupForm" (ngSubmit)="onSubmit()">
 <input type="text" formControlName = "username">
</form>

使用此设置,您可以从表单组中获取控件并评估其状态

.ts

  get controlUsername() {
   return this.SignupForm.get('username');
  }

.html

<button [disabled]="!controlUsername.valid" type="submit">Submit</button> 

推荐阅读