skip to Main Content
<div class="container">
<div class="row">
    <section class="col-3">
        <h5 class="text-warning ml-3">Sort</h5>
        <select class="custom-select mb-3" (change)="onSortSelected($event.target.value)">
            <option *ngFor="let sort of sortOptions" [value] = "sort.value">{{sort.name}}</option>
            
        </select>

I am getting the following error in the ($event.target.value) part value throws an error
: Angular error TS2531: Object is possibly ‘null’

 onSortSelected(sort: string){
  this.sortSelected = sort;
  this.getProducts();
}

2

Answers


  1. You can add change $event.target.value to $event.target?.value
    And then maybe you have to change the Type of the param in onSortSelected
    I dont know how your onSortSelected function looks like, but maybe this works

    onSortSelected(val: YourType): void {
      if (!val) return;
      
      console.log(val);
    }
    
    Login or Signup to reply.
  2. Catch the value in your controller, send all object $event, like this:

    <section>
            <select (change)="onSortSelected($event)">
                   <option
                        *ngFor="let sort of sortOptions"
                        [value] = "sort.value">{{sort.name}}>
                   </option>
            </select>
    </section>
    

    In your controller:

    onSortSelected(value: YourModel) {
        this.selected = value?.target?.value;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search