Angular 2 Date Input not binding to date value

后端 未结 10 1920
醉梦人生
醉梦人生 2021-01-30 16:16

trying to get a form set up but for some reason, the Date input in my html is not binding to the object\'s date value, despite using [(ngModel)]

html:

&l         


        
相关标签:
10条回答
  • 2021-01-30 16:41

    Angular 2 , 4 and 5 :

    the simplest way : plunker

    <input type="date" [ngModel] ="dt | date:'yyyy-MM-dd'" (ngModelChange)="dt = $event">
    
    0 讨论(0)
  • 2021-01-30 16:42

    use DatePipe

    > // ts file
    
    import { DatePipe } from '@angular/common';
    
    @Component({
    ....
    providers:[DatePipe]
    })
    
    export class FormComponent {
    
    constructor(private datePipe : DatePipe){}
    
        demoUser = new User(0, '', '', '', '', this.datePipe.transform(new Date(), 'yyyy-MM-dd'), '', 0, [], []);  
    }
    
    0 讨论(0)
  • 2021-01-30 16:46

    In Typescript - app.component.ts file

    export class AppComponent implements OnInit {
        currentDate = new Date();
    }
    

    In HTML Input field

    <input id="form21_1" type="text" tabindex="28" title="DATE" [ngModel]="currentDate | date:'MM/dd/yyyy'" />
    

    It will display the current date inside the input field.

    0 讨论(0)
  • 2021-01-30 16:49

    Instead of [(ngModel)] you can use:

    // view
    <input type="date" #myDate [value]="demoUser.date | date:'yyyy-MM-dd'" (input)="demoUser.date=parseDate($event.target.value)" />
    
    // controller
    parseDate(dateString: string): Date {
        if (dateString) {
            return new Date(dateString);
        }
        return null;
    }
    

    You can also choose not to use parseDate function. In this case the date will be saved as string format like "2016-10-06" instead of Date type (I haven't tried whether this has negative consequences when manipulating the data or saving to database for example).

    0 讨论(0)
提交回复
热议问题