I have optional fields within my Angular Template form that allows a user to expand an *ngIf statement to show more form fields. However, whenever the the optional fields are filled out and the field is collapsed again the fields are removed from the ngModel. Hopefull the below shows enough detail.
HTML
<form #f="ngForm" (ngSubmit)="submit(f.value)">
<div class="form-group">
<label class="textUnderline" for="inputLocation1">Location:</label>
<input required [(ngModel)]="entry.orgId" name="orgId" maxlength="300" #orgId="ngModel" type="text"
class="form-control" id="inputLocation1" >
</div>
<label class="form-check-label" style="padding-right: 10px;">Exapanded Form Options</label>
<span style="color: #3f51b5; cursor: pointer; padding-top: 0px; top: 10px; font-size: 30px;"
class="glyphicon"
[class.glyphicon-triangle-bottom]="isExpanded"
[class.glyphicon-triangle-top]="!isExpanded"
(click)="toggle()"></span>
<div *ngIf="isExpanded == true">
<div class="form-group">
<label for="problemSummary" class="followUpResponse">Summary:</label>
<p-editor [(ngModel)]="entry.problem" maxlength="4000" #problem="ngModel" name="problem" id="problemSummary"></p-editor>
</div
.ts
toggle() {
this.isExpanded = !this.isExpanded;
}
form json ngModel fields when not expanded
{ "orgId": "DENV (DENVER, CO)"}
form json ngModel fields when expanded
{ "orgId": "DENV (DENVER, CO)", "problem": "I'm A Problem here" }
How do I get (if possible) to have those additional form fields to be passed within my form model no matter if its expanded or collapsed?
Thanks for any help.
Try removing the ngIf and replacing it with [ngStyle]="!isExpanded && {'display': 'none'}"
. Display none will make it so that the div stays in the dom (and therefore stays in the form model). UI should feel the same as before.
The weird ngStyle syntax means:
if (!isExpanded) {
style = display: none
}