typescript Angular 2 ng-必需

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39955807/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:55:26  来源:igfitidea点击:

Angular 2 ng-required

angularjsvalidationangulartypescriptmodel-driven

提问by valiNidelciu

I made a model-driven form in angular 2, and one of the input fields must show up only if a checkbox above is unchecked.I did this with *ngIf. My question is how can I set that input required only if the checkbox is unchecked? In angular 1.x i could make this happen with the ng-required="condition" in the view.

我在 angular 2 中制作了一个模型驱动的表单,只有当上面的复选框未选中时,其中一个输入字段才必须显示。我用 *ngIf 做到了这一点。我的问题是如何仅在未选中复选框的情况下设置所需的输入?在 angular 1.xi 中,视图中的 ng-required="condition" 可以实现这一点。

Here is the html:

这是html:

//the checkbox

//复选框

<div class="checkbox col-sm-9">
   <label>
     <input type="checkbox"  id="getCompanyAddress" style="cursor: pointer;" [formControl]="form.controls['address']" >Use the company address 
  </label>
</div>

// the option input:

// 选项输入:

<div *ngIf="form.value.address == false" class="form-group" [ngClass] = "{'has-error':!form.controls['address'].valid && form.controls['address'].touched}" >
 <label for="add_gestion_adress" class="col-sm-3 control-label">Address
 </label>
  <div class="col-sm-9"><textarea rows="1" id="add_gestion_adress" class="form-control" name="add_gestion_adress" [formControl]="form.controls['address']" ></textarea>
  </div>
</div>

//and the model code:

//和模型代码:

   form: FormGroup;
    constructor(fb:FormBuilder){
      this.form = fb.group({
        'name': [null,Validators.compose([Validators.required, Validators.minLength(1)])],
        'type': ["en gros",Validators.compose([Validators.required, Validators.minLength(2)])],
        'person':[null,Validators.compose([Validators.required, Validators.minLength(1)])],
        'address':[false,Validators.compose([Validators.minLength(1)])],
        'locality':[null, Validators.compose([Validators.required])],
        'county':[null,Validators.compose([Validators.required])],
        'country':[null,Validators.compose([Validators.required])]
      })

    }

采纳答案by qdivision

One way to do it is to listen for value changes in the checkbox form control and add/remove validators in the other control accordingly.

一种方法是监听复选框表单控件中的值更改,并相应地在另一个控件中添加/删除验证器。

Example:

例子:

this.form.get('checkbox-control').valueChanges.map(
      value => {

          if(value) {
              this.form.get('other-control').setValidators(Validators.required);
          }else {
              this.form.get('other-control').clearValidators();
          }

      }
    );

回答by Miller

<textarea [required]="your angular expression">

The above works in the latest version of Angular 4

以上适用于最新版本的Angular 4

回答by Ron Newcomb

The FormBuilder takes a second argument which accepts a validator which is intended for cross-field validation:

FormBuilder 接受第二个参数,该参数接受用于跨字段验证的验证器:

this.form = fb.group({
        'name': [null,Validators.compose([Validators.required, Validators.minLength(1)])],
        'type': ["en gros",Validators.compose([Validators.required, Validators.minLength(2)])],
        'person':[null,Validators.compose([Validators.required, Validators.minLength(1)])],
        'address':[false,Validators.compose([Validators.minLength(1)])],
        'locality':[null, Validators.compose([Validators.required])],
        'county':[null,Validators.compose([Validators.required])],
        'country':[null,Validators.compose([Validators.required])]
      }
    , { validator: this.crossFieldValidation });

You can define it to do whatever.

你可以定义它来做任何事情。

crossFieldValidation(ctrl: FormGroup): ValidationErrors|null {
    let isRequired = ctrl.controls.myCheckbox.value === true;
    let hasValue = ctrl.controls.myMaybeRequiredControlXX.value;
    if (isRequired && !hasValue) return {XXrequired: true};
    return null;
}

To check for the error for display/ngClass, use form.errors?.XXrequiredor whatever key your crossFieldValidation()returned, instead of form.controls.XX.errors?.required.

要检查 display/ngClass 的错误,请使用form.errors?.XXrequiredcrossFieldValidation()返回的任何键,而不是form.controls.XX.errors?.required.