Sorry if this is a duplicate!
So I am trying to have my mat-select
default to the first option in the list. Sounds easy enough, right? Wrong. I am using a modal that pops up to enter a task and am trying to set the default status (which you are only able to select once the project is selected). The compareWith
function works just fine, but once you exit out of the modal and re-enter(without refreshing the page), the second parameter in the compareWith
function is null and the status doesn't default to anything. When exiting the form, I reset it. I am using FormControl
, not ngModel
, just an FYI.
I have tried a couple different compareWith
functions, but only found one that works. I have tried using the [selected]="whatever"
on the select tag but quickly found out through research that it doesn't work for material inputs. I have also tried setting the formcontrol value equal to status when resetting the form. This works, but it is displaying already when I open the modal again. Since the status is disabled until the project is selected, I don't want to show any status on load.
Project select in the html:
<mat-form-field class="form-group">
<mat-select id="project" name="project" placeholder="Project" formControlName="project" [required]="true"
[ngClass]="{'is-invalid': formAddTask.project.errors}">
<mat-option *ngFor="let project of availableProjects" [value]="project.id">{{project.name}}</mat-option>
</mat-select>
<mat-error *ngIf="addTaskForm.get('project').hasError('required')">Project is required</mat-error>
</mat-form-field>
Status select in the html:
<mat-form-field class="form-group">
<div class="input-group"></div>
<mat-select id="status" name="status" placeholder="Status" formControlName="status" [compareWith]="compareObjects">
<mat-option *ngFor="let status of availableStatuses; let i = index" [class.selected]="status === selectedStatus"
[value]="status.id">{{status.name}}</mat-option>
</mat-select>
</mat-form-field>
CompareWith function in ts:
compareObjects(o1: any, o2: any): boolean {
return o1.name === o2.name && o1._id === o2._id;
}
Let me know if there is anything more I need to show!
The status shouldn't have anything in it until the project is selected, once that happens, I'd like the status to default to the first option in the list. What is actually happening is that once the modal is exited and returned to, the default status will no longer display after selecting a project, or it will display on the initial load of the modal, which I want it to only show the default once the project is selected.
Sorry if I was repeating myself too much, I'd rather give too much info than not enough. Thanks in advance, any help is appreciated! :)