繁体   English   中英

Angular 6反应形式-如何设置条件值?

[英]Angular 6 Reactive Form - how to set conditional value?

我在项目中使用Angular 6和Reactive Form。 我有一个关于如何设置条件的问题,例如,如果数据为空则不转换为日期,则将其保留为空。

this.editForm = this.fb.group(
      {
        firstName: [this.user.firstName, Validators.required],
        lastName: [this.user.lastName, Validators.required],        
        workingDate: [
            moment(this.user.workingDate).format("DD/MM/YYYY"),
          Validators.required
        ], ....
       }

我想放置一个条件,例如this.user.workingDate ==“”,然后将其保留为空(如果我们使用moment(),它将改为显示当前日期)

怎么做 ?

你可以尝试一下:

workingDate: [
          this.user.workingDate ? moment(this.user.workingDate).format("DD/MM/YYYY") : null,
          Validators.required
        ], ....

使用三元运算符,您可以设置如下条件

workingDate: [
   (this.user.workingDate ? moment(this.user.workingDate).format("DD/MM/YYYY") : ''), Validators.required
]

Stackblitz示例

this.editForm = this.fb.group(
  { workingDate: [this.user.workingDate ? moment(this.user.workingDate).format("DD/MM/YYYY") : null, Validators.required],
    mobileNo: [this.user.mobileNo ? this.user.mobileNo : null, [Validators.maxLength(11), Validators.minLength(10)]]
   }

从“瞬间”导入*

暂无
暂无

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

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