2

If I have an Angular Form Control as below, what would be the recommended way to format the value?

e.g. I could have a date field returned from the database with seconds and milliseconds etc. How can I format this is a similar way to the date pipe so I just show day, month, year etc?

<input type="text" [formControl]="date">

My typescript file would be as follows:

export class MyForm {

   form: FormGroup;

   ngOnInit(): void {
     this.setupForm();

     this.httpService.get(5).subscribe((response) => {
       this.form.patchValue(response);
     });
   }

   setupForm(): void {
     this.form = new FormGroup({
       date: new FormControl('')
     });
   }
}

1 Answer 1

3

You would need to format the value when you create the control and assign the value in your FormGroup:

const form = new FormGroup({
  date: new FormControl(datePipe.transform(yourData.date, yourFormat)),
});

If you need to populate your value from a service call, you can instantiate the form after the service call completes:

ngOnInit(): void {
  this.httpService.get(5).subscribe((response) => {
    if (response) {
      this.setupForm(response);
    }
  });
}

setupForm(data): void {
  this.form = new FormGroup({
    date: new FormControl(datePipe.transform(data.date, yourFormat)),
  });
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for you reply. How would that work when the record is return from a database? I've expanded my example a bit more. Thanks.
You would want to instantiate your form after your service call completes. If you're using the data other places, you could set a view model property on your class, or you could pass the data as an argument to setupForm(data)
There's no need to instantiate the form, then patch the values. It's much easier to just make your HTTP call, then instantiate the form after you get the data.
That is great. Thanks for your help.

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.