需要Angular 2 ng [英] Angular 2 ng-required

查看:100
本文介绍了需要Angular 2 ng的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用角2制作了模型驱动的表格,并且只有在未选中上面的复选框的情况下,才显示输入字段之一. 我的问题是,仅在未选中此复选框的情况下,如何才能将其设置为必需?在angular 1.x中,我可以通过视图中的ng-required ="condition"来实现这一点.

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.

这是html:

//复选框

<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>

//选项输入:

<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>

//和型号代码:

   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])]
      })

    }

推荐答案

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

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.

示例:

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();
          }

      }
    );

这篇关于需要Angular 2 ng的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆