How to get selected option in change callback of AngularDart component

Issue

I want to use a select HTML element to filter items in a table. For that I have a model value selectedCategoryId and event callback onFilterCategory for the change event. But when callback gets called the value selectedCategoryId is null.

I have the following HTML snippet:

<select id="category"
        class="form-control"
        [(ngModel)]="selectedCategoryId"
        (change)="onFilterCategory()">
    <option *ngFor="let category of categories"
            value="{{category.id}}">
        {{category.name}}
    </option>
</select>

And the following dart snippet:

void onFilterCategory() {
    print('onFilterCategory');
    print('this.selectedCategoryId: ' + this.selectedCategoryId);
}

Do I need to use another callback?

Solution

ngModelChange is the event and $event the value

(ngModelChange)="onFilterCategory($event)"

with

 void onFilterCategory(String value) {

Because you have 2-way binding

[(ngModel)]="selectedCategoryId"

you can also use

(ngModelChange)="onFilterCategory()"

with the onFilterCategory() as it is in your question.

The change event doesn’t work because it fires too early – before [(ngModel)]="selectedCategoryId" was able to update selectedCategoryId.

Answered By – Günter Zöchbauer

Answer Checked By – Cary Denson (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *