Rura daty kątowej nie działa poprawnie w polu tekstowym

Dec 23 2020

My Date Pipe nie działa w Angular. Chcę wyświetlać tylko w tym formacie MM / DD / RRRR ”. Jak to naprawić?

Maszynopis:

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)
});

Dziennik konsoli: środa, 22 lipca 2020 r. 17:18:24 GMT-0700 (czas pacyficzny letni)

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>

Data nie jest wyświetlana jako MM / dd / rrrr i ma dodatkowe daty i godziny, godziny, sekundy itd

Odpowiedzi

2 AshotAleqsanyan Dec 23 2020 at 02:24

Spójrz, nie możesz jednocześnie używać value i formControlName. Pokazuje również wartość kontrolną formularza zamiast wartości atrybutu wartość.

Musisz to obejść. Lubię to

<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

Przeczytałem odpowiedź Ashota Aleqsanyana, która moim zdaniem jest dobra, jeśli chodzi o pieniądze, wcześniej nie zauważyłem, że ustawiłeś wartość zarówno w formControl, jak i na samym wejściu, co wydaje się całkiem błędne.

możesz spróbować z jego roztworem lub spróbować wstrzyknąć rurkę daty bezpośrednio do swojego komponentu i użyć jej w następujący sposób:

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)
});
  }
}

(Założyłem, że inicjalizację wykonujesz w OnInit, w każdym razie możesz oczywiście przesuwać kod po komponencie, jak chcesz)

Myślę, że to powinno ładnie działać :)