在我的表单Validation
中,我的formControlName
无法正常工作。我的表单中有一个fileupload
字段。一旦文件更新,我应该enable
我的submit
按钮。但这种情况并没有发生。
这是我的组件代码:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators, FormBuilder, NgForm } from '@angular/forms';
@Component({
selector: 'app-doc-upload',
templateUrl: './doc-upload.component.html',
styleUrls: ['./doc-upload.component.css']
})
export class DocUploadComponent implements OnInit {
uploadForm:FormGroup;
fileUpload : File = null;
uploadedFileName:string = "Select File...";
constructor(private formbuilder:FormBuilder) {
this.uploadForm = formbuilder.group({
fileUpload : ["", [Validators.required]] //added fro enable
})
}
ngOnInit() {
}
handleFileInput(files:FileList){
this.fileUpload = files.item(0);
this.uploadedFileName = this.fileUpload.name; //works fine
}
}
我的html文件:
<h5>Document Upload</h5>
<form [formGroup]="uploadForm" >
<div class="form-group">
<label for="title" class="cols-sm-2 control-label">Document</label>
<div class="cols-sm-10">
<div class="input-group">
<input type="file" class="custom-file-input" id="exampleInputFile"
(change)="handleFileInput($event.target.files)" aria-describedby="fileHelp" formControlName="fileUpload">
<label class="custom-file-label" for="exampleInputFile">
{{uploadedFileName}}
</label>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group ">
<input type="submit" [disabled]="!uploadForm.valid" value="Generate States" class="btn btn-primary btn-lg btn-block login-button">
</div>
</div>
</div>
</form>
答案 0 :(得分:1)
我不确定您是否可以将文件类型的输入绑定到被动表单。经过一些快速测试,我告诉你。
我这样做是为了单独处理文件。既然你做了,你可以简单地查看按钮的禁用状态:
<input type="submit" [disabled]="fileUpload" value="Generate States" class="btn btn-primary btn-lg btn-block login-button">
答案 1 :(得分:0)
要添加@trichetriche所说的内容,似乎没有出现Angular团队有意在<input type="file" ...>
添加对被动表单的支持,正如您从此处可以看到的{关于此事已被关闭的{3}}。
据说有其他选择,我个人使用以下简单的方法来验证我的文件上传:
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-dynamic-form',
template: `
<form (onsubmit)="submitFile()">
<input type="file" (change)="onFileUpload($event)">
<button type="submit" [disabled]="!fileUpload">Submit</button>
</form>
`
})
export class DynamicFormComponent {
public fileUpload: boolean = false;
constructor() {}
public onFileUpload(event) {
//Do any file validation if needed
this.fileUpload = true;
}
public submitFile() {}
}