【问题标题】:How to set a form validator to true based on conditions?如何根据条件将表单验证器设置为 true?
【发布时间】:2020-07-08 06:16:54
【问题描述】:

如果满足特定条件,我需要将表单中的验证器设为 true。我的代码如下所示

ngOnInit() {
    this.joinee = JSON.parse(sessionStorage.getItem('joinee'));
    this.Id = this.joinee.JoineeID;
    this.isPersonalDocumentsVerified = this.joinee.isPersonalDocumentsVerified;
    this.personalDocForm = this.fb.group({
      photograph: ['', Validators.required],
      resume: ['', Validators.required],
      aadhaar: [''],
      panCard: [''],
      passport: [''],
      drivingLicense: [''],
      votersId: ['']
    });

    
    this.uploadService.getData(this.Id).subscribe(
      result => {
        this.uploads = result;


        if (this.uploads[0].photographUrl !== null) {
          
         //make the validators of photograph in personalDocForm to true here
          
        }
        

      },
      error => {
        
        throw error;
      }
    );
  }

如果数据来自后端,我需要将照片字段的验证设置为 true。

提前致谢。

【问题讨论】:

  • 您正在根据表单定义中的要求设置照片,因此为了满足该条件,您需要将照片控件设置为某个值,大概是 url。你可以使用 this.personalDocForm.patchValue({ photo: this.uploads[0].photographUrl })

标签: angular typescript validation angular-forms form-control


【解决方案1】:

当有photographUrl时,你只需要将照片url设置为photograph控件

if (this.uploads[0].photographUrl !== null) {
   this.personalDocForm.get('photograph').setValue(this.uploads[0].photographUrl)
}

【讨论】:

  • 实际上表单中的照片只接受文件(IForm 文件到后端)...Url 是另一回事
【解决方案2】:

StackBlitz link 中的工作演示

你需要在subscribe()方法中setValue()的图片控件。

turnTrue(){
   this.photo.patchValue(true, {emitModelToViewChange: false});
}
get photo(){
  return this.formData.controls['photo'];
}

以下是模板 html 代码,您可以在照片为真时触发验证..

{{formData.value | json}}
 <div *ngIf="photo.value === true">
     Photo is Empty
 </div>
 <button (click)="turnTrue()">Photo to True </button>

【讨论】:

  • 控制台 DOMException 出现以下错误:无法在 'HTMLInputElement' 上设置 'value' 属性:此输入元素接受文件名,该文件名只能以编程方式设置为空字符串。
  • @RobyA 检查更新答案。现在错误已经消失了。只需将选项传递给patchValue(true, {emitModelToViewChange: false}
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-26
  • 1970-01-01
  • 2018-06-11
  • 2023-04-01
  • 2022-11-18
  • 2020-09-12
相关资源
最近更新 更多