Angular:表单验证无效

Angular: Form Validation not working

我有一个表单,要求在提交表单时必须填写标题、显示和图像字段。我能够验证 "Title" 和 "Display" 字段,但 "Image" 字段未通过验证以禁用提交按钮。

我正在尝试使用“!heroForm.form.valid || togglefile”之类的管道来验证表单,但它不起作用。任何帮助都会很棒。以下是我的参考代码:

表格:

<div class="row innerpage">
  <form (ngSubmit)="onSubmit()" #heroForm="ngForm">
    <div class="form-group col-xs-6">
      <label for="newstitle">News Title (Required):</label>
      <input type="text" class="form-control" [(ngModel)]="news.newstitle" id="newstitle" name="newstitle" required #newstitle="ngModel"/>
      <div [hidden]="newstitle.valid || newstitle.pristine" class="alert alert-danger">
          News Title is required
      </div>
    </div>                   

    <div class="form-group col-xs-6">
      <label for="display">Display (Required):</label><br>
      <ss-multiselect-dropdown [options]="myOptions" [(ngModel)]="optionsModel" (ngModelChange)="onChange($event)" [texts]="myTexts" [settings]="mySettings" name="display" required #display="ngModel"></ss-multiselect-dropdown>           
      <div [hidden]="display.valid || display.pristine" class="alert alert-danger">
          Display is required
      </div>
    </div>          

    <div class="form-group col-xs-6">
            <label for="formData">News Image:</label>
            <input #fileInput type="file" id="formData" name="formData" multiple="true" (change)="fileChange($event)" required>
    </div>             

    <div class="form-group col-xs-12">
      <button type="submit" class="btn btn-success" [disabled]="!heroForm.form.valid || togglefile">Add</button>
  </form>
</div>

分量:

export class NewsAddComponent {
  @ViewChild('fileInput') fileInput:ElementRef;
fileList;
togglefile: boolean;

ngOnInit() { this.getNewss() }

  getNewss() {
    this.togglefile = true;
  }  

fileChange(event) {
    this.fileList = event.target.files;
    console.log(this.fileList);
    console.log(this.fileList.length);
    if (this.fileList.length == 0) {
        this.togglefile == true;
    } else if (this.fileList.length > 0) {
        this.togglefile == false;
    }
  }
}

问题是,而不是分配(使用=true/false value for togglefile variable,你比较它(使用==)。

解决方法如下:

fileChange(event) {
  this.fileList = event.target.files;
  if (this.fileList.length == 0) {
    this.togglefile = true;
  } else if (this.fileList.length > 0) {
     this.togglefile = false;
  }
}

甚至更好:

fileChange(event) {
  this.fileList = event.target.files;
  this.togglefile = this.fileList.length === 0;
}