DEV Community

loading...

Angular Select Binding

jwp profile image John Peters Updated on ・1 min read

Dropdown for all U.S. States

<select 
  #selector 
  // Allows for seeing the selected item
  // And which address has changed
  (change)="onAddrChanged(selector, addr)">
  <option
   // All U.S. states
   *ngFor="let state of states"
   // Select only the state in addr.state
   [selected]="addr.state === state.name"
   >
   // Show the user each state.name 
   {{ state.name }}
  </option>
</select>

Enter fullscreen mode Exit fullscreen mode

What's not shown here is how the addr property was bound.

Specification

  • Create a dropdown for selecting any State in the U.S.
  • The dropdown is not allowed multi-select
  • The current State (Name) of the Address must be Selected (if there is one).
  • Any change must notify the Typescript method onAddrChanged with the Selector element and the address.
  • The backend persists all changes at proper time.

The State model is:

export class State {
   id: number;
   // user only sees this field
   name: string;
   code: string;
}
Enter fullscreen mode Exit fullscreen mode

The States array is:

states: Array<State>
Enter fullscreen mode Exit fullscreen mode

The Address Model


export class Address {
   id: number;
   street: string;
   street2: string;
   cityID: number;
   city: string;
   stateID: number;
   state: string;
   stateCode: string;
   zip: number;
   zip4: number;
   cities: any;
}

Enter fullscreen mode Exit fullscreen mode

When updating the backend on changes for city or state, the Put request only contains the cityID and stateID.

As close to the metal as we can get! We do not need any 3rd party Select component.

JWP 2020

Discussion (0)

Forem Open with the Forem app