首页 > 解决方案 > 如何在 html“值”属性中使用字符串插值

问题描述

我使用以下内容在 component.ts 文件中生成日期:

this.myDate=new Date();

并尝试在 html 表单值字段中使用。但没有加载任何内容。我尝试了以下语法但没有成功

<input type="datetime" class="form-control" id="date" value={{this.myDate}} name="created" ngModel>

<input type="datetime" class="form-control" id="date" [value]=[this.myDate] name="created" ngModel>

另一个问题是我的 json 文件在添加操作后只更新了空字符串

标签: angular

解决方案


您缺少输入类型 datetime 的正确日期格式,即 ="2017-06-01T08:30"

在 component.ts

formatted_date:string;

ngOnInit(){
//your code...
this.formatted_date = this.myDate.toISOString();
this.formatted_date.slice(0,16);
}

在 template.html 中(将类型更改为 datetime-local 因为 datetime 已过时MDN Doc

<input type="datetime-local" class="form-control" id="date" value="{{formatted_date}}" name="created">

推荐阅读