0

My code is here.

I have a select box. I added an "onchange" event handler to handler the on change event.

Unfortunately, the browser prompts me:

updateSelectedSystem is not defined

However, I have defined the updateSelectedSystem function in app.component.ts.

How can I fix the problem?

Alternatively, is it possible to make a grouped selection list using angular material component (i.e. mat-selection-list)?

The KNVB
  • 3,588
  • 3
  • 29
  • 54

2 Answers2

1

For select elements in Angular, you have to use change and wrap it with parenthesis in app.component.html. You will also need to add ngModel and bind a variable to it:

<select 
  #availableSystem
  multiple
  matNativeControl
  style="height:300px;width:150px"
  [(ngModel)]="selectedSystem"
  (change)="updateSelectedSystem()">
  <optgroup *ngFor="let division of sharedDivisionList" [label]="division">
    <option *ngFor="let system of divisionToSystem[division]" [value]="systemToCalltree[system].callTreeId">
      {{system}}
    </option>  
  </optgroup>
</select>

And in your app.component.ts, declare the variable and use it in updateSelectedSystem():

selectedSystem = '';
...

updateSelectedSystem() {
  console.log(this.selectedSystem);
}

More details in this answer.

HaniBhat
  • 353
  • 1
  • 9
1

You currently have a <select>, and you want to listen for changes in its selected value. You are attempting to do this by calling a function in your component in the onChange handler.

<select onChange="updateSelectedSystem(availableSystem(availableSystem))">
  <!-- options -->
</select>  

This is not how you handle form control changes in Angular. You could use [(ngModel)] to bind to a property, and use (onModelChange) to listen to value changes. This is a simple approach for simple scenarios.

I would recommend using forms, as forms are more flexible when you want to add complexity, and are still simple to set up.

To do this, build your form in your component:

constructor(private formBuilder: FormBuilder) {}

form: FormGroup;   
selected: number[];

ngOnInit() {
  this.form = this.formBuilder.group({
    systems: this.formBuilder.control([])
  });
}

onChange() {
  this.selected = this.form.value.systems;
}

And bind to your HTML using the forms directives:

<form [formGroup]="form" (change)="onChange()">
  <select multiple formControlName="systems">
    <!-- options -->
  </select>  
</form>

As your form grows in complexity, the form directives mirror the structure of the form group you build in your component.

The simple version

You can always just bind to the change event on the select directly:

<select (change)="onChange()">
  <!-- options -->
</select>

DEMO: https://stackblitz.com/edit/angular-k3k2nn

Kurt Hamilton
  • 12,490
  • 1
  • 24
  • 40