I have a reactive form in which we are using input type of date. The form control is binding inside a loop in this case I am not able to apply the date pipe because there is no ngmodel binding to it.
Expected date controls : dd/mm/yyyy
Currently its binding this way :
Stackblitz in which i tried my code : https://stackblitz.com/edit/angular-date-input-using-reactive-forms-a4yyn5?file=app%2Fapp.component.ts
Following html template code:
<form [formGroup]="loginForm">
<div *ngFor="let order of [0, 1, 2]; let i = index">
<label formArrayName="requestdate">
<input type="date" rows="1" class="form-control" [formControlName]="i" />
</label>
</div>
</form>
Following TYPESCRIPT code
import { Component } from '@angular/core';
import { FormArray, FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
loginForm: FormGroup;
constructor(
private formBuilder: FormBuilder
) { }
ngOnInit() {
this.loginForm = this.formBuilder.group({
requestdate: new FormArray([])
})
}
get requestDatesArray(){
return this.loginForm.controls['requestdate'] as FormArray;
}
}
Can someone please help us to bind the date controls with dd/mm/yyyy format.
The problem in your code is that you haven't bound form control in ts code so the best solution is to add form control to form array once you get the array [0,1,2] like this:
HTML
<form [formGroup]="loginForm" (ngSubmit)="onSubmit()">
<div *ngFor="let order of requestDatesArray.controls; let i = index">
<label formArrayName="requestdate">
<input type="date" rows="1" class="form-control"
[formControlName]="i" />
</label>
</div>
<button type="submit">SUbmit</button>
</form>
TypeScript
loginForm: FormGroup;
yourArr = [0, 1, 2] // This should be a string like (new Date().toISOString().slice(0,10)) to bind it to HTML in the initialization
constructor(
private formBuilder: FormBuilder
) { }
ngOnInit() {
this.loginForm = this.formBuilder.group({
requestdate: new FormArray([])
})
this.yourArr.forEach(el => {
this.addToFormArray(el)
})
}
addToFormArray(el:number) {
let control = new FormControl(el)
this.requestDatesArray.push(control)
}
onSubmit() {
console.log(this.loginForm)
}
get requestDatesArray(){
return this.loginForm.controls['requestdate'] as FormArray;
}