Issue
Learning Angular 17 and having issues with form-select values binding to the nested class ClientLocations
in class Projects
.
My modal
form
<div class="form-group row pt-1 pb-1">
<label for="txtNewClientLocations" class="col-sm-4 form-select-label pt-2">Client Locations</label>
<div class="col-sm-6">
<select class="form-select" [(ngModel)]="newProject.clientLocationID" name="ClientLocation" aria-label="Please Select" id="txtNewClientLocations">
<option default value="null">Please Select</option>
<option *ngFor="let clientLocation of clientLocations" [value]="clientLocation.clientLocationID">{{clientLocation.clientLocationName}}</option>
</select>
</div>
</div>
My Project
class:
export class Project {
projectID: number|null;
projectName: string|null;
dateOfStart: string|null;
teamSize: number|null;
active: boolean;
status: string|null;
clientLocationID: number|null;
clientLocation: ClientLocation|null;
constructor(){
this.projectID = null;
this.projectName = null;
this.dateOfStart = null;
this.teamSize = null;
this.active = true;
this.status = null;
this.clientLocationID = null;
this.clientLocation = new ClientLocation();
}
}
export class ClientLocation {
clientLocationID: number;
clientLocationName: string;
constructor(){
this.clientLocationID = -1;
this.clientLocationName = "";
}
}
For all other form elements, able to look and register the values to the backend. However, the this form-select is not able to add the values to the ClientLocations
nested class in the Projects
class. It just shows up as default constructor values of newProject
variable.
Solution
You can add the change event to update the property clientLocation
based on the dropdown data clientLocations
and the selected ID in clientLocationID
The select is setting the value as string, but ID is generally a number, to make the find work properly you need to use ==
which does not strictly check the types and the object will get matched!
setClientLocation() {
this.newProject.clientLocation = this.clientLocations.find((item: ClientLocation) =>
item.clientLocationID == this.newProject.clientLocationID) || null;
}
In the HTML, on change of the dropdown, we can add (ngModelChange)
and trigger the above function to update the property clientLocation
based on the selection!
<div class="form-group row pt-1 pb-1">
<label for="txtNewClientLocations" class="col-sm-4 form-select-label pt-2">Client Locations</label>
<div class="col-sm-6">
<select class="form-select" [(ngModel)]="newProject.clientLocationID" name="ClientLocation" aria-label="Please Select" id="txtNewClientLocations">
<option default value="null">Please Select</option>
<option *ngFor="let clientLocation of clientLocations" [value]="clientLocation.clientLocationID">{{clientLocation.clientLocationName}}</option>
</select>
</div>
</div>
Answered By - Naren Murali
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.