0
votes

I am attempting to create a select in my Angular app based on a classificationsList array from the component. As of now, the view initiates with the first value already "selected", but validation marks it as an invalid response.

default but not valid

If I select the dropdown and choose the other option, it returns valid.

(before selection)

enter image description here

(after selecting)

enter image description here

But when I go back to select "Class 1" it registers as invalid again.

What I'm expecting this to do is have the default, empty option (like below), that disappears once a real option is selected. The difference between these two lists is that the classificationsList is dynamic, whereas the the department list is static.

enter image description here

enter image description here

In fact, I took the html block from the department list and just added the *ngFor piece. Can someone tell me what I'm doing incorrectly, here? The issue isn't strictly with the validation, however. The bigger issue is the fact that it defaults to the first value in the array instead of an empty value like Department. When I put an empty string into the first item of the array from the component side, it selects the empty value like it selects "Class 1" as you've seen.

The validation actually performs fine here, as the empty string is invalid, and the rest of the array items are valid. In this scenario, though, there is an empty string still available in the option.

enter image description here

<div><label for="titleClass">Title Classification</label></div>
  <select name="titleClass" id="titleClass" ngModel required>
    <option *ngFor="let class of classificationsList">{{class}}</option>
  </select>
</div>
1
How are you displaying the valid/invalid visual cues? stackblitz.com/edit/angular-31l9d2 looks fine here.Jeto
Can you try putting default value attribute to your option?alokstar
@Jeto The red/green markers on the side. That's not entirely clear in the pictures. The validation works well everywhere elseMyStackFlowethOver
@MyStackFlowestOver I saw those, I'm asking where they come from. <select>s do not come with that stuff out of the box :) Also did you check the StackBlitz?Jeto
@Jeto They come from a validation method in the component. I have updated the question with some more information.MyStackFlowethOver

1 Answers

0
votes

I got it! The functionality I was looking for required me to set a default value (unattached to the array). For this one, I set the default as null like below.

<div class="formBoxRows">
  <div><label for="titleClass">Title Classification</label></div>
  <select name="titleClass" id="titleClass" ngModel required>
    <option *ngFor="let class of classificationsList" [value]=null>{{class}}</option>
  </select>
</div>