0

select-option loop at myComponent.html:


      <select class="form-select" (change)="selectOption($event)">
        <option *ngFor="let entity of entities; let i = index"
          value="{{entity.id}}" [selected]="i == 0 ? true : null" 
          (onload)="fooFunction(i, entity.id)">{{entity.name}}
        </option>
      </select>

and myComponent.ts function:


  fooFunction(i: number, entityId: number){
    console.log(`${i} - ${entityId}`);
  }

I want to pass variables to function while populating options. I tried load , onload , onSelect etc.

How can I achieve this in angular13?

2 Answers 2

1

Your selectOption($event) could reflect that by passing your variables in an array on change.

In TS

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  entities = [
    { id: 1, name: 'hello' },
    { id: 2, name: 'test' },
  ];

  selectOption(event: any) {
    const arr = event.target.value.split(',');
    console.log(arr[0]); //id
    console.log(arr[1]); //index
  }
}

Html

<select class="form-select" (change)="selectOption($event)">
  <option *ngFor="let entity of entities; let i = index" [value]="[entity.id, i]">
    {{ entity.name }}
  </option>
</select>

Working example: https://stackblitz.com/edit/angular-ivy-qzdsfl?file=src%2Fapp%2Fapp.component.ts

Sign up to request clarification or add additional context in comments.

1 Comment

(change)="selectOption($event)" passes variables perfectly but the problem is that this solution needs a change i.e. click event. Unlike this case, variables need to be passed when loading options without any click or change. So, the answer needs to be edited.
0

You have to use ngModel

 <select class="form-select"  [(ngModel)]="selectedValue">
        <option *ngFor="let entity of entities; let i = index"
          [ngValue]="entity.id">{{entity.name}}
        </option>
 </select>

1 Comment

Support for using the ngModel has been deprecated in Angular v6. For more information: angular.io/guide/deprecations

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.