La tubería de fecha angular no funciona correctamente en el cuadro de texto

Dec 23 2020

Mi Date Pipe no funciona en Angular. Solo quiero mostrar como este formato MM / dd / aaaa '. ¿Cómo se puede arreglar?

Mecanografiado:

this.testDate = new Date(this.singleUser.createDate);
console.log(this.testDate); 

this.userForm = new FormGroup({
  userName: new FormControl(this.singleUser.userName),
  email: new FormControl(this.singleUser.email),
  createDate: new FormControl(this.singleUser.createDate)
});

Registro de la consola: miércoles 22 de julio de 2020 17:18:24 GMT-0700 (hora de verano del Pacífico)

HTML:

<mat-form-field class="row" appearance="outline" floatLabel="always">
    <mat-label>Created Date</mat-label>
    <input matInput [readonly]="true" formControlName="createDate" [value] = "testDate | date: 'MM/dd/yyyy'" >
</mat-form-field>

La fecha no se muestra como MM / dd / aaaa y tiene fecha y hora adicionales, segundos, etc.

Respuestas

2 AshotAleqsanyan Dec 23 2020 at 02:24

Mira, no puedes usar value y formControlName al mismo tiempo. También muestra su valor de control de formulario en lugar de valor por atributo de valor.

Necesita agregar alguna solución para eso. Como esto

<mat-form-field class="row" appearance="outline" floatLabel="always">
    <mat-label>Created Date</mat-label>
    <input matInput [readonly]="true" (change)="funcFromTs($event.target.value)" [value] = "testDate | date: 'MM/dd/yyyy'" >
</mat-form-field>

Ts

funcFromTs(value: string) {
   this.userForm.get('createDate').patchValue(value);
}
2 DarioPiotrowicz Dec 23 2020 at 02:20

Leí la respuesta de Ashot Aleqsanyan, que creo que es correcta en cuanto al dinero, no me di cuenta antes de que estableciste el valor tanto en formControl como en la entrada en sí, lo que parece bastante incorrecto.

puede probar con su solución o también intentar inyectar la tubería de fecha directamente en su componente y usarlo así:

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

@Component({
   providers: [DatePipe]   // you need to provide datepipe in providers list for your component
})
class YourComponent implements OnInit {

  constructor(private datePipe: DatePipe) {}

  ngOnInit(){
       // you don't want the testDate field
       // this.testDate = new Date(this.singleUser.createDate);

       const createDate = this.datePipe.transform(this.singleUser.createDate, 'yyyy-MM-dd');
       console.log(createDate); 

       this.userForm = new FormGroup({
         userName: new FormControl(this.singleUser.userName),
         email: new FormControl(this.singleUser.email),
         createDate: new FormControl(createDate)
});
  }
}

(Supuse que haces tu inicialización en OnInit, de todos modos puedes mover el código alrededor del componente como quieras, por supuesto)

Creo que esto debería funcionar bien :)