我试图通过属性绑定设置日期类型输入的默认值。
首先,我在app.component.ts中创建了一个新的日期对象,然后将date的[value]
属性绑定到app.component.ts中的currentDate
属性。但它不起作用
//表单模板
<section class="container">
<div class="panel panel-default">
<div class="panel-heading">Add a Task</div>
<div class="panel-body">
<form class="form-horizontal" [formGroup]="taskForm" (ngSubmit)="onSubmit()">
<div class="form-group">
<label for="title" class="col-sm-2 control-label">Title *</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="taskTitle" placeholder="Title of Task" formControlName="taskTitle">
</div>
</div>
<div class="form-group">
<label for="description" class="col-sm-2 control-label">Description *</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="description" placeholder="Enter Your Description" formControlName="description">
</div>
</div>
<div class="form-group">
<label for="date" class="col-sm-2 control-label">Date of Completion *</label>
<div class="col-sm-10">
<input type="date" class="form-control" id="date" formControlName="date" [value]="currentDate">
</div>
</div>
<div class="form-group">
<div class="col-md-offset-6">
<button type="submit" class="btn btn-default">Submit your data</button>
</div>
</div>
</form>
</div>
</div>
</section>
<section class="container">
<app-task-list></app-task-list>
</section>
//应用程序组件
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
currentDate: {};
taskForm: FormGroup;
ngOnInit() {
this.taskForm = new FormGroup({
'taskTitle': new FormControl(''),
'description': new FormControl(''),
'date': new FormControl(null)
});
this.currentDate = new Date();
console.log(this.currentDate);
}
onSubmit() {
}
}
答案 0 :(得分:2)
如果日期不是表单/输入所期望的格式,则不会显示日期。您可以转换组件中的日期或使用管道。
使用竖管:
<form>
<input
type="date" class="form-control"
name="currentDate" [ngModel]="currentDate | date:'yyyy-MM-dd'">
</form>
无管道:
组件:
currentStringDate;
constructor() {
this.currentStringDate = new Date().toISOString().substring(0, 10);
}
HTML:
<input type="date" class="form-control" name="currentStringDate" [ngModel]="currentStringDate">
编辑:不要忘记在你的html中使用名称标签,它需要与ngModel变量同名