简体   繁体   English

角反应形式选择默认值和对象ID

[英]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). 我有一个验证此选项的问题,因为该字段与数据库中另一个集合的对象ID(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. 如果我将其设置为null ,它可以工作,但不会在第一个实例中向我显示该消息。

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'),
  })
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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