javascript - Reactive form validation treats default 'select' value of select input box as valid -


i have been struggling validate reactive form default "select" option select input box when there's no value selected. if value present in form need select respective value.

i using reactive form , below code implementation:

<select class="form-control" formcontrolname="environment" >     <option disabled [value]="null">-- select --</option>     <option *ngfor="let ami of envs" [value]="ami.amiid">         {{ami.name}}     </option> </select> 
this.onlinetestform = this._fb.group({             .             .                 environment: ['', validators.required],             .             .                  });  //value present in model (<formcontrol>this.onlinetestform.controls['environment'])            .setvalue(this.model.environment, { onlyself: true });  //value not present in model (<formcontrol>this.onlinetestform.controls['environment'])            .setvalue('null', { onlyself: true }); 

is there better way achieve above?

your problem seem here:

(<formcontrol>this.onlinetestform.controls['environment'])        .setvalue('null', { onlyself: true }); 

you setting string value 'null' instead of null. string 'null' of course valid value.

also setting complete object value of form control if exists, though environment expects id, @ least have specified in template:

[value]="ami.amiid" 

i see 2 options here "improve" code. these depend on if this.model gets values asynchronously or not. if know value of this.model on initialization, can this:

environment: [this.model.environment ? this.model.environment.amiid : null,                validators.required] 

here must remember initialize model empty object, undefined error not thrown in case there no value in model.


the other option see, if model value set asynchronously, use one-way-binding:

<select formcontrolname="environment" [ngmodel]="model?.environment?.amiid"> 

and have in build of form:

environment: [null, validators.required] 

usually not recommend using ngmodel reactive form, two-way binding here big no-no me. have 2 bindings, both ngmodel , formcontrol in ts. can cause unexpected behavior. one-way-binding okay here, since angular sets value , doesn't care happens model after in ts. chose one-way-binding here, since looks cleaner in opinion. can of course skip , use setvalue instead after receiving value.

here demo both options, other 1 commented out: plunker


Comments

Popular posts from this blog

javascript - Create a stacked percentage column -

Optimising Firebase database by automatically overwriting data -

javascript - Angular UI-Grid customTemplate directive causing rows to load slowly/? -