Sandeep Thomas
Sandeep Thomas

Reputation: 4727

Array find not working when search again object.value. But its working when specifying value directly

I'm facing a weird issue.

<select [(ngModel)]="selectedBudget.year" name="" class="form-control" id="">
                  <option value="2020">2020</option>
                  <option value="2021">2021</option>
                </select>

and here is my function to search for a value based on the year selected.

  addBudget(){
    alert(this.selectedBudget.year);//shows 2021
    alert(this.locations.find(p=>p.year=== 2021).locationName); here it shows the location name
    alert(this.locations.find(p=>p.year=== this.selectedBudget.year).locationName); //here it trigger error
/*     let rc = this.locations.find(x => x.locationName === this.selectedBudget.locationName && 
      x.year === this.selectedBudget.year).cost; //resource cost
      alert(rc); */
      console.info(this.locations);

  }

As I mentioned in the internal comments after each alerts, it triggers an error Cannot read property locationName of undefined. But the weird thing is its working the line just above that.

So 2021 when I specify as value directly it returns but when checking against the property its not working.

Is there is anything wrong with the way I specified ngModel. Mine is a pre-populated dropdown.

Upvotes: 0

Views: 62

Answers (1)

Kurt Hamilton
Kurt Hamilton

Reputation: 13515

You are setting string values by doing value="2021". This means the strict equality comparison of p.year === 2021 fails because the types are different.

Instead, bind the numeric values to the options using [ngValue]. This will mean that the selected value is now numeric, and your strict equality check will pass.

<select [(ngModel)]="selectedBudget.year" class="form-control">
  <option [ngValue]="2020">2020</option>
  <option [ngValue]="2021">2021</option>
</select>

Upvotes: 1

Related Questions