Как я могу выполнять события щелчка в раскрывающемся списке (Angular)? - PullRequest
0 голосов
/ 19 июня 2020

У меня есть две кнопки (месяц, год), которые реагируют на разные события ... Теперь я хотел бы вставить эти события в select. Подскажите, пожалуйста, как это работает?

Мой код:

// Solution with buttons
<button class="menu-button" type="button" mat-raised-button [ngClass]="{'active': selectedMenuLeft === 'monthButton'}" (click)="activateButton(1)">Monat</button>
<button class="menu-button" type="button" mat-raised-button [ngClass]="{'active': selectedMenuLeft === 'yearButton'}" (click)="activateButton(2)">Jahr</button>
 activateButton(check) {
    if (check === 1) {
      this.selectedMenuLeft = 'monthButton';
      this.navService.sendNavEventUpdate('month');
    } else {
      this.selectedMenuLeft = 'yearButton';
      this.navService.sendNavEventUpdate('year');
    }
  }
// The same with a select. What do I have to optimize?
<select class="upload_slc" required title="">
<!-- Options -->
<option value="content" *ngFor="let navValue of menuLeftMobile" [value]="navValue">
{{ navValue }}
</option>
</select>
// Menu left in mobile
  menuLeftMobile: Array<string> = ['Monat', 'Jahr'];

Ответы [ 3 ]

1 голос
/ 19 июня 2020
<mat-select placeholder="Select Menu" name="nav_value" 
    (selectionChange)="menuChangeAction(nav_value)"
        [(ngModel)]="nav_value">
        <mat-option *ngFor="let navValue of menuLeftMobile"
          [value]="navValue">{{ zone.label }}</mat-option>
      </mat-select>

В вашем компоненте вы можете сделать следующее:

nav_value: any;

menuChangeAction(value) {
    console.log(value) // you will get your selected value here
}
1 голос
/ 19 июня 2020

Самый простой способ

<select #mySelect (change)='onOptionsSelected(mySelect.value)'>

И функция будет такой

 activateButton(check) {
    if (check === "Monat") {
      this.selectedMenuLeft = 'monthButton';
      this.navService.sendNavEventUpdate('month');
    } else {
      this.selectedMenuLeft = 'yearButton';
      this.navService.sendNavEventUpdate('year');
    }
  }

Надеюсь, это сработает для вас

1 голос
/ 19 июня 2020

Вы можете сделать это с помощью двусторонней привязки к ngModel директиве.

Контроллер

menuLeftMobile: Array<string> = ['Monat', 'Jahr'];
selected: string;

onChange() {
  if (selected === 'Monat') {
    this.selectedMenuLeft = 'monthButton';
    this.navService.sendNavEventUpdate('month');
  } else {
    this.selectedMenuLeft = 'yearButton';
    this.navService.sendNavEventUpdate('year');
  }
}

Шаблон

<select class="upload_slc" required title="" [(ngModel)]="selected" (change)="onChange()">
  <!-- Options -->
  <option value="content" *ngFor="let navValue of menuLeftMobile" [value]="navValue">
  {{ navValue }}
  </option>
</select>

Теперь вам не нужны дополнительные переменные selectedMenuLeft для установки класса. Вы можете использовать selected в шаблоне.

<div [ngClass]="{'active': selected === 'Monat'}"></div>
...