我需要使用带有[formGroup]
和formGroupName="field"
<form [formGroup]="generalForm" (ngSubmit)="onSubmit()">
<input class="form-control" placeholder="yyyy-mm-dd"
formControlName="dateIni" ngbDatepicker #a="ngbDatepicker">
</form>
Component.ts
generalForm: FormGroup;
ngOnInit() {
this.generalForm = this.formBuilder.group({
name: ['', Validators.required],
dateIni: ['', Validators.required],
dateFin: ['', Validators.required],
registerDateLimit: ['', Validators.required],
});
}
在我的代码中,我尝试设置默认值:
public dateIni: { year: 2017, month: 8, day: 8 };
或
@Input() dateIni: { year: 2017, month: 8, day: 8 };
但它没有采用默认值,所有文档仅提及模板表单的情况。
任何想法我应该怎么做?
答案 0 :(得分:1)
dateIni: ['', Validators.required],
你需要把你的初始值放在这里
dateIni: ['2014-01-01', Validators.required],
格式正确
答案 1 :(得分:0)
我也遇到了同样的问题,并使用下面的代码片段解决了
import { Component, OnInit, EventEmitter } from '@angular/core';
import { FormBuilder, Validators, FormArray, FormGroup } from '@angular/forms';
import { DatePipe } from '@angular/common';
@Component({
selector: 'app-profile',
templateUrl: './profile.component.html',
styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {
generalForm: FormGroup;
constructor(
private fb: FormBuilder,
private datePipe: DatePipe) { }
ngOnInit() {
this.intilizeForm();
const dateIni = "2018-12-08"
const iniYear = Number(this.datePipe.transform(dateIni, 'yyyy'));
const iniMonth = Number(this.datePipe.transform(dateIni, 'MM'));
const iniDay = Number(this.datePipe.transform(dateIni, 'dd'));
this.generalForm.controls.dateIni.setValue({
year: iniYear ,
month: iniMonth ,
day: iniDay
});
}
intilizeForm(): void {
// Here also we can set the intial value Like dateIni:[ {year:2018,month:08, day: 12}, .....
this.generalForm = this.fb.group({
name: ['', Validators.required],
dateIni: ['', Validators.required],
dateFin: ['', Validators.required],
registerDateLimit: ['', Validators.required],
});
}