user1993412
user1993412

Reputation: 862

Date pipe in Angular formControlName

Can someone please guide me to implement date pipe in angular 8 with formControlName

train.component.html

<mat-grid-tile colspan=1 rowspan=1>
    <div class="train-control">
        <input type="text" formControlName="{{ 'apprTimestamp' | date:'medium' }}">
    </div>
</mat-grid-tile>

But does not not seemed to work. Can some one please guide me.

Exception

TrainComponent.html:58 ERROR Error: InvalidPipeArgument: 'Unable to convert "apprTimestamp" into a date' for pipe 'DatePipe'
    at invalidPipeArgumentError (common.js:5737)
    at DatePipe.transform (common.js:6877)
    at checkAndUpdatePureExpressionInline (core.js:34381)
    at checkAndUpdateNodeInline (core.js:35155)
    at checkAndUpdateNode (core.js:35090)
    at debugCheckAndUpdateNode (core.js:36112)
    at debugCheckDirectivesFn (core.js:36055)
    at Object.eval [as updateDirectives] (TrainComponent.html:60)
    at Object.debugUpdateDirectives [as updateDirectives] (core.js:36043)
    at checkAndUpdateView (core.js:35055)

Thanks !

Upvotes: 1

Views: 6852

Answers (2)

AVJT82
AVJT82

Reputation: 73357

You can use the datepipe in the component as well, and modify the date from there. This will only work once, with a preset date. But you are also not including anything else in your question, so we can completely omit that.

So I suggest the following:

import { DatePipe } from '@angular/common';

@Component({
  selector: '...',
  templateUrl: '...',
  styleUrls: ['...'],
  providers: [DatePipe]
})

Inject it in the constructor and then use::

constructor(private fb: FormBuilder, private datePipe: DatePipe) {
  this.myForm = this.fb.group({
    field1: [this.datePipe.transform(new Date(), 'medium')]
  })
}

Then remove the pipe from the template.

STACKBLITZ

Upvotes: 4

Vandesh
Vandesh

Reputation: 6894

Exclude the '' with the variable containing the timestamp value, if you really want to assign the date value to the formControlName.

<input type="text" name="someName" formControlName="{{ apprTimestamp | date:'medium' }}">

Upvotes: -5

Related Questions