網站搜尋

html - Angular 2 日期輸入無法綁定到日期值


試著設置一個表單,但不知為何,我的 HTML 中的日期輸入欄位並沒有綁定到物件的日期值,儘管我使用了 [(ngModel)]

html :

<input type='date' #myDate [(ngModel)]='demoUser.date'/><br>

表單元件:

export class FormComponent {
    demoUser = new User(0, '', '', '', '', new Date(), '', 0, [], []);  
}

使用者類別:

export class User {
    constructor (
        public id: number,
        public email: string,
        public password: string,
        public firstName: string,
        public lastName: string,
        public date: Date,
        public gender: string,
        public weight: number,
        public dietRestrictions: string[],
        public fitnessGoals: string[]
    ){

    }
}

測試輸出顯示當前的「新」日期作為物件的值,但輸入並未更新使用者物件的日期值或反映該值,這表明這兩個雙向綁定都無法正常運作。非常感謝您的幫助。

答案#1

Angular 2、4 和 5:

最簡單的方法:plunker

<input type="date" [ngModel] ="dt | date:'yyyy-MM-dd'" (ngModelChange)="dt = $event">

答案#2

你可以使用以下方式來取代 [(ngModel)]:

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

你也可以選擇不使用 parseDate 函數。在這種情況下,日期將以字串格式保存,例如 "2016-10-06",而不是 Date 類型(我還沒有嘗試過這在處理數據或保存到資料庫時是否會有負面影響)。

答案#3

在你的元件中

let today: string;

ngOnInit() {
  this.today = new Date().toISOString().split('T')[0];
}

以及在你的 HTML 文件中

<input name="date" [(ngModel)]="today" type="date" required>

答案#4

在 .ts 中:

today: Date;

constructor() {  

    this.today =new Date();
}

.html:

<input type="date"  
       [ngModel]="today | date:'yyyy-MM-dd'"  
       (ngModelChange)="today = $event"    
       name="dt" 
       class="form-control form-control-rounded" #searchDate 
>