Html Angular 2 日期输入不绑定到日期值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38175251/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular 2 Date Input not binding to date value
提问by MoSheikh
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)]
试图设置一个表单,但由于某种原因,尽管使用了 [(ngModel)],我的 html 中的 Date 输入并未绑定到对象的日期值
html:
html:
<input type='date' #myDate [(ngModel)]='demoUser.date'/><br>
form component:
表单组件:
export class FormComponent {
demoUser = new User(0, '', '', '', '', new Date(), '', 0, [], []);
}
User class:
用户类:
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[]
){
}
}
A test output reveals the current "new" Date as the object's value, but the input doesn't update the User object's date value or reflect the value, suggesting neither of the two-way bindings are working. Help would be greatly appreciated.
测试输出显示当前“新”日期作为对象的值,但输入不会更新用户对象的日期值或反映该值,这表明双向绑定都不起作用。帮助将不胜感激。
回答by Bougarfaoui El houcine
回答by hakany
Instead of [(ngModel)] you can use:
而不是 [(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;
}
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).
您也可以选择不使用 parseDate 函数。在这种情况下,日期将保存为字符串格式,如“2016-10-06”而不是日期类型(例如,我还没有尝试过在操作数据或保存到数据库时这是否会产生负面影响)。
回答by Matiullah Karimi
In your component
在您的组件中
let today: string;
ngOnInit() {
this.today = new Date().toISOString().split('T')[0];
}
and in your html file
并在您的 html 文件中
<input name="date" [(ngModel)]="today" type="date" required>
回答by user10121373
In .ts :
在 .ts 中:
today: Date;
constructor() {
this.today =new Date();
}
.html:
.html:
<input type="date"
[ngModel]="today | date:'yyyy-MM-dd'"
(ngModelChange)="today = $event"
name="dt"
class="form-control form-control-rounded" #searchDate
>
回答by Andrei Zhytkevich
Angular 2 completely ignores type=date
. If you change type to text
you'll see that your input
has two-way binding.
Angular 2 完全忽略了type=date
. 如果您将 type 更改为 ,text
您将看到您input
具有双向绑定。
<input type='text' #myDate [(ngModel)]='demoUser.date'/><br>
Here is pretty bad advise with better one to follow:
这是一个非常糟糕的建议,有更好的建议可以遵循:
My project originally used jQuery
. So, I'm using jQuery datepicker
for now, hoping that angular team will fix the original issue. Also it's a better replacement because it has cross-browser support. FYI, input=date
doesn't work in Firefox.
我的项目最初使用jQuery
. 所以,我现在正在使用jQuery datepicker
,希望 angular 团队能够解决最初的问题。它也是一个更好的替代品,因为它具有跨浏览器支持。仅供参考,input=date
在Firefox 中不起作用。
Good advise: There are few pretty good Angular2 datepickers
:
好的建议:有几个不错的Angular2 datepickers
:
回答by Shivam
As per HTML5, you can use
input type="datetime-local"
instead of
input type="date"
.
根据 HTML5,您可以使用
input type="datetime-local"
代替
input type="date"
.
It will allow the [(ngModel)]
directive to read and write value from input control.
它将允许[(ngModel)]
指令从输入控件读取和写入值。
Note:If the date string contains 'Z' then to implement above solution, you need to trim the 'Z' character from date.
注意:如果日期字符串包含“Z”,那么要实现上述解决方案,您需要从日期中修剪“Z”字符。
For more details, please go through this linkon mozilla docs.
有关更多详细信息,请访问mozilla 文档上的此链接。
回答by M Rameez
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, [], []);
}
回答by Daniel Ashcraft
If you are using a modern browser there's a simple solution.
如果您使用的是现代浏览器,则有一个简单的解决方案。
First, attach a template variable to the input.
首先,将模板变量附加到输入。
<input type="date" #date />
Then pass the variable into your receiving method.
然后将变量传递到您的接收方法中。
<button (click)="submit(date)"></button>
In your controller just accept the parameter as type HTMLInputElement and use the method valueAsDate on the HTMLInputElement.
在您的控制器中,只需接受类型为 HTMLInputElement 的参数并在 HTMLInputElement 上使用 valueAsDate 方法。
submit(date: HTMLInputElement){
console.log(date.valueAsDate);
}
You can then manipulate the date anyway you would a normal date.
然后,您可以按照正常日期的方式操作日期。
You can also set the value of your <input [value]= "...">
as you
would normally.
您还可以<input [value]= "...">
像往常一样设置您的值。
Personally, as someone trying to stay true to the unidirectional data flow, i try to stay away from two way data binding in my components.
就我个人而言,作为试图忠于单向数据流的人,我尽量避免组件中的双向数据绑定。
回答by tecnocrata
you can use a workaround, like this:
您可以使用一种解决方法,如下所示:
<input type='date' (keyup)="0" #myDate [(ngModel)]='demoUser.date'/><br>
on your component :
在您的组件上:
@Input public date: Date,
回答by Deepak Bhattarai
In Typescript - app.component.ts file
在 Typescript - app.component.ts 文件中
export class AppComponent implements OnInit {
currentDate = new Date();
}
In HTML Input field
在 HTML 输入字段中
<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.
它将在输入字段内显示当前日期。