如何在角度4中的<input type =“file”/>上使用必需的验证

时间:2017-07-05 14:25:41

标签: javascript angular validation

文字输入正常。我使用相同的文件,但它无法正常工作。

<input type="text" name="title" #title="ngModel" ngModel required class="form-control" placeholder="Title Here">
<div *ngIf="title.errors && (title.dirty || title.touched)">
    <span class="help-block error" [hidden]="!title.errors.required"> Title 
      is Required 
    </span>
</div>
<input type="file" #image="ngModel" (change)="fileEvent($event)" 
name="image" ngModel>

1 个答案:

答案 0 :(得分:0)

如果您只想显示/隐藏依赖于所选文件的错误消息

@Component({
  selector: 'my-app',
  template: `
    <div>
       <input type="file" (change)="onChange($event)" name="image">
      <div *ngIf="!fileSelected">
      <span class="help-block error" [hidden]="!fileSelected"> 
        File is Required 
      </span>
     </div>
    </div>
  `,
})
export class AppComponent {
  onChange(event) {
    var files = event.srcElement.files;
    console.log(files);
    this.fileSelected = files.length>0;
  }
}