简体   繁体   中英

Angular reactive forms select default value and object id

I have a selector with a default value, which is actually a message to select the option. I have a problem to validate this option, since the field is linked with the object id of another collection in the database (mongoose-express js).

<div class="col-lg-6 form-group">
  <label for="professional_t">Assign professional</label>
  <select formControlName="professional_t" id="professional_t" name="professional_t" class="form-control">
    <option value="">Select Professional</option>
    <option *ngFor="let p of professionals" [value]="p._id"> {{ p.name}} </option>
  </select>
</div>

In the component:

this.forma = new FormGroup({
  /* ... */
  'turno': new FormGroup({
    'date_t': new FormControl(null),
    'professional_t': new FormControl(''),
  })
})

If I set it as null , it works but it does not show me the message in the first instance.

The validation error:

professional_t:
    kind: "ObjectID"
    message: "Cast to ObjectID failed for value "" at path "professional_t""
    name: "CastError"
    path: "professional_t"

Try to add some value to the default select option instead of living it as blank.

May be you can try adding some unique number or string and then initialize that value in the reactive form for that field.

Example:

<div class="col-lg-6 form-group">
  <label for="professional_t">Assign professional</label>
  <select formControlName="professional_t" id="professional_t" name="professional_t" class="form-control">
    <option value="DefaultProfessionaValue">Select Professional</option>
    <option *ngFor="let p of professionals" [value]="p._id"> {{ p.name}} </option>
  </select>
</div>



this.forma = new FormGroup({
  /* ... */
  'turno': new FormGroup({
    'date_t': new FormControl(null),
    'professional_t': new FormControl('DefaultProfessionalValue'),
  })
})

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