简体   繁体   中英

Angular2 form validation on certain conditions

I have setup a form with form builder and i would like to setup custom validation based on a value change

So this is my form

 constructor(){

 this.newtruck  = this._formbuilder.group(
  {
    'trucktype':[''],
    'transporter':[''],
    'dropdown_transporter':[''],
    'truck_number':[''],
    'dropdown_truck_number':[''],
    'driver_name':[''],
    'dropdown_driver_name':[''],
    'driver_number':[''],
    'material':[''],
  }
 )

}

On a dropdown change a value is passed to this function

updateSelectedValue(item) {

if(item){
  if(item.dropdown == 1) {
    this.newtruck.setControl("dropdown_transporter", new FormControl('', Validators.required));
    this.newtruck.setControl("dropdown_transporter", new FormControl('', Validators.required));
    this.newtruck.setControl("dropdown_driver_name", new FormControl('', Validators.required));

  } else  if(item.dropdown == 0){
     this.newtruck.reset();

    this.newtruck.setControl("transporter", new FormControl('', Validators.required));
    this.newtruck.setControl("truck_number", new FormControl('', Validators.required));
   this.newtruck.setControl("driver_name", new FormControl('', Validators.required));
    this.newtruck.setControl("driver_number", new FormControl('', Validators.required));
}
}

}

Now on the form i have a button that i set enbled or disabled by

<button ion-button icon-rig color="danger" [disabled]="!newtruck.valid" (click)="onCreate()" > Save
      <ion-icon name="send"></ion-icon>

    </button>

The above button is always disabled even form is instantiated what could be wrong as you can see at first no validators are called

You can build the condition into the validator by wrapping the validator by your custom validator function.

this.newtruck.setControl("dropdown_transporter", 
  new FormControl('', 
    (control:Control) => { 
      if(item && item.dropdown == 1) {
      return Validators.required(control)
      }
    )
  );

You can also move out the whole function like

updateSelectedValue(item) 

  var requiredValidator = (control:Control) => { 
    if(item && item.dropdown == 1) {
      return Validators.required(control)));
    }
  };

  this.newtruck.setControl("dropdown_transporter", 
    new FormControl('', requiredValidator));
  ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM