Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 ng-required

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.

Here is the 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])]
      })

    }
like image 954
valiNidelciu Avatar asked Oct 10 '16 10:10

valiNidelciu


People also ask

What is Ng required?

Definition and Usage The ng-required directive sets the required attribute of a form field (input or textarea). The form field will be required if the expression inside the ng-required attribute returns true. The ng-required directive is necessary to be able to shift the value between true and false .

What is Ng repeat in angular?

Definition and Usage. The ng-repeat directive repeats a set of HTML, a given number of times. The set of HTML will be repeated once per item in a collection. The collection must be an array or an object. Note: Each instance of the repetition is given its own scope, which consist of the current item.

What is Ng form in AngularJS?

The ng-form Directive in AngularJS is used to create a nested form i.e. one form inside the other form. It specifies an inherit control from the HTML form. It creates a control group inside a form directive which can be used to determine the validity of a sub-group of controls.

What is pristine in angular?

ng-pristine The field has not been modified yet. ng-dirty The field has been modified. ng-valid The field content is valid. ng-invalid The field content is not valid.


3 Answers

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

The above works in the latest version of Angular 4

like image 145
Miller Avatar answered Oct 28 '22 20:10

Miller


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

      }
    );
like image 39
qdivision Avatar answered Oct 28 '22 20:10

qdivision


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

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?.XXrequired or whatever key your crossFieldValidation() returned, instead of form.controls.XX.errors?.required.

like image 32
Ron Newcomb Avatar answered Oct 28 '22 20:10

Ron Newcomb