I need to use ReactiveForms, with [formGroup]
and 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],
});
}
In my code, I tried to put a default value:
public dateIni: { year: 2017, month: 8, day: 8 };
or
@Input() dateIni: { year: 2017, month: 8, day: 8 };
but it is not taking the default value and all the docs only mention the case with template forms.
Any Idea how should I do it ?
In short ngModel can't be used by itself within FormGroup When you use formControlName, ngModel does not activate or create a control (it's simply used as an @Input). formControlName just links to the existing input you created in your class.
[formControl] assigns a reference to the FormControl instance you created to the FormControlDirective . formControlName assigns a string for the forms module to look up the control by name.
FormControlNamelink Syncs a FormControl in an existing FormGroup to a form control element by name.
dateIni: ['', Validators.required],
you need to put your initial value here like
dateIni: ['2014-01-01', Validators.required],
in correct format
I have faced the same problem and resolved using below code snippet
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],
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With