각도 날짜 파이프가 텍스트 상자에서 올바르게 작동하지 않음

Dec 23 2020

내 Date Pipe가 Angular에서 작동하지 않습니다. MM / dd / yyyy '형식으로 만 표시하고 싶습니다. 어떻게 고칠 수 있습니까?

Typescript :

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

콘솔 로그 : 2020 년 7 월 22 일 수요일 17:18:24 GMT-0700 (태평양 일광 절약 시간)

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>

날짜가 MM / dd / yyyy로 표시되지 않고 추가 datetime 시간 초 등이 있습니다.

답변

2 AshotAleqsanyan Dec 23 2020 at 02:24

값과 formControlName을 동시에 사용할 수 없습니다. 또한 값 속성 별 값 대신 양식 제어 값을 표시합니다.

이에 대한 해결 방법을 추가해야합니다. 이렇게

<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

나는 돈에 옳다고 생각하는 Ashot Aleqsanyan의 대답을 읽었습니다. 나는 당신이 formControl과 입력 자체 모두에서 값을 설정했다는 것을 알지 못했습니다.

그의 솔루션으로 시도하거나 날짜 파이프를 구성 요소에 직접 삽입하고 다음과 같이 사용할 수도 있습니다.

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

(나는 당신이 OnInit에서 초기화를한다고 가정했지만, 어쨌든 당신이 원하는대로 컴포넌트 주위로 코드를 이동할 수 있습니다)

나는 이것이 잘 작동 할 것이라고 생각한다. :)