HTML日期选择器的角度设置默认值

cod*_*110 3 html binding datetime date angular

[(ngModel)] 没有为日期选择器设置默认值。我尝试了各种不同的方法来填充日期选择器,但一直无法做到。

我的 HTML

<input id="START_DATE" type="datetime-local" [(ngModel)]="startDate"/>
Run Code Online (Sandbox Code Playgroud)

在该示例中,绑定有效,但我无法设置默认值。

如果我只是插入值,我可以设置该值,但是我失去了我的 2 路绑定。value="{{startDate}}"

You*_*r M 5

Plunker - https://plnkr.co/edit/s5OMg2olU2yHI246nJOG?p=preview

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


小智 5

您可以将字符串类型属性绑定到输入日期类型。您必须将“日期对象”转换为“字符串”并将字符串值存储在类组件属性中。将相应的属性(组件类)绑定到 HTML 元素(模板)。

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  startDate = new Date().toISOString().slice(0, 16);

  constructor(){
  }
}
Run Code Online (Sandbox Code Playgroud)

您还可以根据用例创建可自定义的“日期到字符串”格式函数。