How can I set my reactive form date input value?

前端 未结 3 1206
傲寒
傲寒 2021-02-08 13:30

So I am trying to display this date for an input. But it\'s not displaying when setting the value of it in my form builder group. I would also like to be able to format it too.<

相关标签:
3条回答
  • 2021-02-08 13:42

    Try the built-in formatDate package.

    import { formatDate } from '@angular/common' 
    

    and then convert your date and set it to the datepicker control

    this.yourForm.controls.controlName.setValue(formatDate(date,'yyyy-MM-dd','en'));
    
    0 讨论(0)
  • 2021-02-08 13:59

    You have two possibilities to set you date as default value.

    Variant 1:

    For setting default date value to <input> tag with type date you should use HTML-property value of input-tag.

    Example:

    <form [formGroup]="editForm2">
        <input type="date" formControlName="startDate" value="{{ post.startDate | date:'yyyy-MM-dd' }}">
        <input type="date" formControlName="endDate" value="{{ post.endDate | date:'yyyy-MM-dd' }}">
    </form>
    

    Variant 2 (recommended):

    You can use an built-in function formatDate() in angular.

    Step 1:

    Import formatDate() from @angular/common in you component typescript file.

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

    Note: formatDate(yourDate, format, locale) expects 3-4 parameters.

    Step 2:

    Format your dates in definition of your form group.

    this.editForm = this.formBuilder.group({
          startDate: [formatDate(this.post.startDate, 'yyyy-MM-dd', 'en'), [Validators.required]],
          endDate: [formatDate(this.post.endDate, 'yyyy-MM-dd', 'en'), [Validators.required]]
    });
    

    Here is working example: https://stackblitz.com/edit/angular-kucypd

    Here is documentation of input type date: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/date

    0 讨论(0)
  • 2021-02-08 14:01

    Another solution, a little more functional w time zone Offset, adding binding and format transformation:

    .html:

    <form [formGroup]="form">
    <input type="date" class="form-control" (change)="onMyDateChange($event)" name="myDate" formControlName="myDate" value="{{ actualDateFormGroup | date:'yyyy-MM-dd' }}" >
    </form>
    

    .ts:

     actualDateFormGroup = new Date(new Date().getTime() - (new Date().getTimezoneOffset() * 60000)).toISOString().split("T")[0];
    
     onMyDateChange(event: any) {
        this.forma.patchValue({ myDate: event.target.value });
      }
    

    Then you can modify the format obtained in the myDate variable as needed in the code.

    For example: 2019-10-13 to 20191013

     stringFormat(string){
      let date = fechaString.replace(/-/g, '');
      return date;
      }
    
    finalDate = stringFormat(myDate);
    
    0 讨论(0)
提交回复
热议问题