Reputation: 3
Using reactive-forms sample application I have added curr_date form control which has a pipe to format the date in desired format. In ts file, form group has the curr_date property which has preset value in different format.
<form [formGroup]="profileForm" (ngSubmit)="onSubmit()">
<label for="first-name">First Name: </label>
<input id="first-name" type="text" formControlName="firstName" required>
<label for="last-name">Last Name: </label>
<input id="last-name" type="text" formControlName="lastName">
<label for="zip">Date: </label>
** <input id="curr_date" type="text" formControlName="curr_date" [value]="profileForm.value.curr_date | date: 'MM/dd/yyyy'">**
<div formGroupName="address">
<h2>Address</h2>
<label for="street">Street: </label>
<input id="street" type="text" formControlName="street">
<label for="city">City: </label>
<input id="city" type="text" formControlName="city">
<label for="state">State: </label>
<input id="state" type="text" formControlName="state">
<label for="zip">Zip Code: </label>
<input id="zip" type="text" formControlName="zip">
</div>
<div formArrayName="aliases">
<h2>Aliases</h2>
<button type="button" (click)="addAlias()">+ Add another alias</button>
<div *ngFor="let alias of aliases.controls; let i=index">
<!-- The repeated alias template -->
<label for="alias-{{ i }}">Alias:</label>
<input id="alias-{{ i }}" type="text" [formControlName]="i">
</div>
</div>
<p>Complete the form to enable button.</p>
<button type="submit" [disabled]="!profileForm.valid">Submit</button>
</form>
<hr>
<p>Form Value: {{ profileForm.value | json }}</p>
<p>Form Status: {{ profileForm.status }}</p>
<button type="button" (click)="updateProfile()">Update Profile</button>
In ts file, I have added curr_date formcontrol as follows:
export class ProfileEditorComponent {
profileForm = this.fb.group({
firstName: ['', Validators.required],
lastName: [''],
curr_date: ['2008-03-28T00:00:00', Validators.required],
address: this.fb.group({
street: [''],
city: [''],
state: [''],
zip: [''],
}),
aliases: this.fb.array([
this.fb.control('')
])
});
Here is what I noticed,
The element has FormControlName attribute and the date is not formatted as per date pipe
FormControlName attribute is removed from element and the date is now formatted as per date pipe
Any help to resolve this issue is highly appreciated. Thanks!
Upvotes: 0
Views: 127
Reputation: 223
Might be super easy
<input id="curr_date" type="text" ...
change that to
<input id="curr_date" type="date" ...
You shouldn't have to deal with any type of conversion or anything else.
Also, only use formControlName
or value
but never both. If you have a reactive form built, then set the value in the TS and not in the HTML.
Upvotes: 0