1

I use Angular 6 and Reactive Form in my project. I have a question about how to set a condition, for example if the data is empty then don't convert to date, leave it empty.

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
        ], ....
       }

I want to put a conditional like if the this.user.workingDate == "" then leave it empty (if we use moment(), it will display the current date instead)

how to do that ?

2
  • 1
    Using terinary(?) operator, you can set the condition Commented Sep 12, 2018 at 9:32
  • thank you i just know that we can use tertinary operators inside array Commented Sep 12, 2018 at 11:59

3 Answers 3

2

Can you try this :

workingDate: [
          this.user.workingDate ? moment(this.user.workingDate).format("DD/MM/YYYY") : null,
          Validators.required
        ], ....
Sign up to request clarification or add additional context in comments.

Comments

1

Using the terinary operator, you can set the condition like below

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

Stackblitz example

Comments

0
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)]]
   }

import * as moment from 'moment'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.