0

I am facing issue, where I cannot set team's club to [selected] option with [ngValue]. However, if I'm using [value] and [selected], it set's team's club to the option, but I cannot pass object with [value]

Here is my code:

Using [value] and [selected], which sets team's club to [selected] option, but I cannot pass object to the [value]

<select
    *ngIf="isEditing"
    name="club"
    #club="ngModel"
    [ngModel]="team?.club">
    Change club's logo
    <option
        *ngFor="let item of premierLeagueTeams"
        [value]="item"
        [selected]="item === team?.club">
        {{ item.club }}
    </option>
</select>

Using [ngValue], but options field doesn't have team's club when I start editing.

<select
    *ngIf="isEditing"
    class="team-club-change"
    name="club"
    #club="ngModel"
    [ngModel]="team?.club.clubName"
    (change)="changeTeam(club.value)">
    Change club's logo
    <option
        *ngFor="let item of premierLeagueTeams"
        [ngValue]="item">
        {{ item.clubName }}
    </option>
</select>

interfaces

export interface Team {
    name: string,
    club: Club,
    id: number
}

export interface Club {
    clubName: string, 
    logoURL: string,
    venue: string,
    city: string
}

2 Answers2

0

NgModel directive works as a bridge that enables "two-way binding" to HTML elements. Using "two-way binding" we can display a data property as well as update that property when the user makes changes & we can achieve this in both component and HTML elements.

Pattern: ngModel in property binding and ngModelChange in event binding. Link => change event

Note: If two-way binding is taking place at HTML element levels such as in input box or select box then we will use ngModel for target name as [(ngModel)]

Moreover: [value] supports string values, whereas [ngValue] supports any type, and to use objects as value, use [ngValue] instead of [value].

Possible Error: This ngModel directive is defined in one of the Modules called Forms and by default this is not imported in to application. If you want to use ngModel or if you wanna build any kind of forms you need to explicitly import FormsModule in app.module.ts

Know more about two-way data binding and ngModel on these links Link - 1 Link - 2

Abhishek Duppati
  • 610
  • 6
  • 18
-1

Instead of (change) You have to use (ngModelChange). This answer has a very good explanation about both of them.

B45i
  • 2,368
  • 2
  • 23
  • 33