加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

形式 – 角度2 – 使用带有可选字段的ngControl

发布时间:2020-12-17 09:28:50 所属栏目:安全 来源:网络整理
导读:我很难试图在表单中使用* ngIf,而ngFormModel会验证表单. 用例是:根据用户输入,隐藏或停用表单中的某些特定字段.但是,如果显示这些输入,则必须对其进行验证. 当只需要基本验证时,我可以做一个或另一个: 如果仅需要输入,则使用ngControl并且需要使用A-OK 如
我很难试图在表单中使用* ngIf,而ngFormModel会验证表单.

用例是:根据用户输入,隐藏或停用表单中的某些特定字段.但是,如果显示这些输入,则必须对其进行验证.

当只需要基本验证时,我可以做一个或另一个:

>如果仅需要输入,则使用ngControl并且需要使用A-OK
>如果需要特定的格式,可以使用pattern属性.这不是Angular,但它有效.

但是为了实现更复杂的验证,我一直在尝试使用ngControl耦合到ngFormModel,以便使用自定义检查.我使用了以下页面中的代码:

How to add form validation pattern in angular2(和那里引用的链接)

Angular2 Forms :Validations,ngControl,ngModel etc

我的代码如下:

HTML

<div>
  <h1>Rundown of the problem</h1>
  <form (ngSubmit)="submitForm()" #formState="ngForm" [ngFormModel]="myForm">
    <div class="checkbox">
      <label>
        <input type="checkbox" [(ngModel)]="model.hideField" ngControl="hideField"> Is the input below useless for you ?
      </label>
    </div>

    <div *ngIf="!model.hideField">
      <div class="form-group">
        <label for="optionalField">Potentially irrelevant field </label>
        <input type="text" class="form-control" [(ngModel)]="model.optionalField" ngControl="optionalField" required #optionalField="ngForm">
        <div [hidden]="optionalField.valid || optionalField.pristine" class="alert alert-warning">
          This input must go through myCustomValidator(),so behave.
        </div>
      </div>
    </div>

    <button type="submit" class="btn btn-primary" [disabled]="!formState.form.valid">I can't be enabled without accessing the input :(</button>
    <button type="submit" class="btn btn-default">Submit without using form.valid (boo !)</button>
  </form>
</div>

打字稿

import {Component,ChangeDetectorRef,AfterViewInit } from 'angular2/core';
import {NgForm,FormBuilder,Validators,ControlGroup,FORM_DIRECTIVES}    from 'angular2/common';

@Component({
  selector: 'accueil',templateUrl: 'app/accueil.component.bak.html',directives:[FORM_DIRECTIVES],providers: [FormBuilder]
})
export class AccueilComponent implements AfterViewInit {

  private myForm: ControlGroup;
  model: any;

  constructor(fb: FormBuilder,cdr: ChangeDetectorRef) {
    this.cdr = cdr ;

    this.model = {} ;
    this.myForm = fb.group({
      "hideField": [false],"optionalField": [this.model.optionalField,Validators.compose([this.myCustomValidator])]
    });
  }

  ngAfterViewInit() {
    // Without this,I get the "Expression has changed after it was checked" exception.
    // See also : https://stackoverflow.com/questions/34364880/expression-has-changed-after-it-was-checked
    this.cdr.detectChanges();
  }

  submitForm(){
    alert("Submitted !");
  }

  myCustomValidator(optionalField){
    // Replace "true" by "_someService.someCheckRequiringLogicOrData()"
    if(true) {
      return null;
    }

    return { "ohNoes": true };
  }
}

即使使用* ngIf从模板中删除输入,构造函数仍在引用该控件.这反过来阻止我使用[disabled] =“!formState.form.valid”,因为myForm可以理解为INVALID.

我正在瞄准可能使用角度2吗?我相信这不是一个常见的用例,但是再一次使用我目前的知识,我看不出我能如何工作.

谢谢 !

您可以尝试做的是重置您的控件上的验证器.这意味着,当您想要一组新的验证器由于状态更改而被绑定到控件时,您将重新定义验证器函数.

在你的情况下,当你勾选/取消选中你的复选框你想要发生以下情况:

>将输入设置为可选(不需要),但仍然对您的自定义验证器进行验证.
>当复选框被取消选中时,将控件的验证器还原到原始状态.
>再次验证控件,以便更新form.valid.

See my plnkr sample based on Angular.io’s Forms Guide

if (optional)
   this.heroFormModel.controls['name'].validator = Validators.minLength(3);
else
   this.heroFormModel.controls['name'].validator =
        Validators.compose([Validators.minLength(3),Validators.required]);

this.heroFormModel.controls['name'].updateValueAndValidity();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读