Search code examples
angulardata-binding

Angular Mat-multiple-select, getting the data from the dropdown list


HTML:
  <mat-form-field>
  <mat-label>Choose terms</mat-label>
  <mat-select [formControl]="termlist" multiple>
  <mat-option required *ngFor="let term of terms" [value]="term.termName"  
  >
  {{term.termName}}
  </mat-option>
  </mat-select>
  </mat-form-field>
  <button mat-flat-button color="primary" 
  (click)="openSelectComponent()">Continue</button>    

Typescript file:

     termlist = new FormControl();
       terms: Term;
       constructor(private termHttpService: TermHttpService, private router: 
       Router) { }
       ngOnInit() {
       this.termHttpService.get().subscribe(result => {
      this.terms = result;
      console.log(result);
    });

  }
  openSelectComponent() {
    this.router.navigate(['/termselected'])
  }
}

So the main point is how do I get the values from the multiple select(terms) and pass them out to the next component?

So the data from here:

https://gyazo.com/49bbcddf17bee2f44d7a1a4579568ee0

How do I get into these selected values?


Solution

  • Add a event OnSelectionChange on select -

    your HTML

     <mat-form-field>
      <mat-label>Choose terms</mat-label>
      <mat-select [formControl]="termlist" multiple>
      <mat-option (onSelectionChange)="getValues($event)" required *ngFor="let term of terms" [value]="term.termName"  
      >
      {{term.termName}}
      </mat-option>
      </mat-select>
      </mat-form-field>
      <button mat-flat-button color="primary" 
      (click)="openSelectComponent()">Continue</button>  
    

    your component.ts

     getValues(event: {
        isUserInput: any;
        source: { value: any; selected: any };
      }) {
        if (event.isUserInput) {
          if (event.source.selected === true) {
            console.log(event.source.value)
          } else {
            console.log(event.source.value)
          }
        }
      }
    

    Note: event.source.selected === true defined the checkbox is checked