Угловое множественное значение флажка - PullRequest
1 голос
/ 06 ноября 2019

Студент хочет зарегистрировать один класс или несколько классов. Поскольку список классов является динамическим, я использовал ngFor для отображения в табличном формате с флажком в конце и для выбора класса. Но не знаю, как получить значение, когда ученик установил флажок для выбора класса.

Я пытался использовать опцию выбора, но это не удавалось.

<div>
<table align="center" >
  <tr class="heading" >
    <th style="padding: 5px;">Code</th>
    <th style="padding: 5px;">Name</th>
    <th style="padding: 5px;">Capacity</th>
    <th style="padding: 5px;">Remaining</th>
    <th style="padding: 5px;">Location</th>
    <th style="padding: 5px;">Instructor</th>
    <th style="padding: 5px;">Register?</th>
  </tr>
  <tr *ngFor="let item of classItem">
    <td style="border-right-style: dashed;">{{ item.Code }}</td>
    <td>{{ item.Name }}</td>
    <td>{{ item.Capacity }}</td>
    <td>{{ item.Remaining }}</td>
    <td>{{ item.Location }}</td>
    <td>{{ item.Instructor }}</td>
    <td>
      <ion-checkbox style="text-align: center;" (onchange)="checkboxChange()" [(ngModel)]="checkItem"></ion-checkbox>
    </td>

  </tr>
</table>

Я ожидаютогда, когда учащийся зарегистрируется в каком-либо классе, вместимость класса будет уменьшена на единицу и обновлена ​​до базы данных Firebase.

Ответы [ 3 ]

1 голос
/ 06 ноября 2019

Поскольку у вас есть несколько флажков, вам нужен массив для отслеживания этих флажков.

Компонент:

checkboxes = [];

Инициализируйте все флажки с falseчтобы не проверять их в начале.

ngOnInit() {
  // This array will be the same length as the iterable object used in *ngFor.
  this.checkboxes = new Array(this.classItem.length).fill(false);
}

Шаблон:

В шаблоне свяжите каждый флажок с соответствующим значением.

<tr *ngFor="let item of classItem; let i = index">
  ...
  <ion-checkbox style="text-align: center;" (onchange)="checkboxChange(i)"
    [(ngModel)]="checkboxes[i]"></ion-checkbox>
  ...
</tr>

Если флажок установлен или снят, измените доступную емкость класса.

checkboxChange(i) {
  if (this.checkboxes[i]) {
    this.capacity++;
  } else {
    this.capacity--;
  }
}
0 голосов
/ 06 ноября 2019
<table align="center" >
  <tr class="heading" >
    <th style="padding: 5px;">Code</th>
    <th style="padding: 5px;">Name</th>
    <th style="padding: 5px;">Capacity</th>
    <th style="padding: 5px;">Remaining</th>
    <th style="padding: 5px;">Location</th>
    <th style="padding: 5px;">Instructor</th>
    <th style="padding: 5px;">Register?</th>
  </tr>
  <tr *ngFor="let item of classItem;let i = index">
    <td style="border-right-style: dashed;">{{ item.code }}</td>
    <td>{{ item.name }}</td>
    <td>{{ item.capacity }}</td>
    <td>{{ item.remaining }}</td>
    <td>{{ item.location }}</td>
    <td>{{ item.instructor }}</td>
    <td>
      <ion-checkbox style="text-align: center;" (ionChange)="checkboxStateChanged(i)" [checked]="item.checked"></ion-checkbox>
    </td>


  </tr>

  </table>

в вашем ts:

classSelectedIndexes : number[] = []; //storing the selected item indexes just in case  

checkboxStateChanged(index : number){
 this.item[i].checked= !this.item[i].checked;
 if(this.item[i].checked){
  //do something if true
 }
  else{
  //do something if false
 }
}

Ожидается, что в вашем classItem свойство checked все будет инициализировано false

т.е. ваш classItem должен иметь тип:

interface ClassType {
code : string; 
name : string ; 
capacity: string ; 
remaining : number ; 
location : string ; 
instructor : string; 
checked: boolean; 
}
0 голосов
/ 06 ноября 2019

Вот мое решение вашей проблемы. Сначала я добавил компонентный файл ts с фиктивными данными в массиве checkItem типа ClassDescription с интерфейсом ClassDescription. Обратите внимание, что вместо этого я использовал обычный флажок ввода html, я только что проверил на ионной документации, и он будет работать так же, как показано ниже: Ionic Checkbox

<table align="center" >
  <tr class="heading" >
    <th style="padding: 5px;">Code</th>
    <th style="padding: 5px;">Name</th>
    <th style="padding: 5px;">Capacity</th>
    <th style="padding: 5px;">Remaining</th>
    <th style="padding: 5px;">Location</th>
    <th style="padding: 5px;">Instructor</th>
    <th style="padding: 5px;">Register?</th>
  </tr>
  <tr *ngFor="let item of classItem">
    <td style="border-right-style: dashed;">{{ item.code }}</td>
    <td>{{ item.name }}</td>
    <td>{{ item.capacity }}</td>
    <td>{{ item.remaining }}</td>
    <td>{{ item.location }}</td>
    <td>{{ item.instructor }}</td>
    <td>
      <input type="checkbox"  [(ngModel)]="item.register"  (change)="onChecked(item)" 
[disabled]="(item.remaining === 0) && item.register == !true"> 

      <br>
    </td>


  </tr>

  </table>

Мое решение Stackblitz здесь Stackblitz solution. Далее вы можете добавить свою логику для firebase внутри функции onChecked.

    import { Component } from '@angular/core';

    interface ClassDescription {
    code : string; 
    name : string ; 
    capacity: string ; 
    remaining : number ; 
    location : string ; 
    instructor : string; 
    register: boolean; 
    }
   @Component({
   selector: 'my-app',
   templateUrl: './app.component.html',
   styleUrls: [ './app.component.css' ]
   })
  export class AppComponent  {

     onChecked(item) {
     if(item.register)
       {
         item.remaining = item.remaining - 1 ;
       }
      else{
          item.remaining = item.remaining + 1 ;
        }  

     }

    classItem: ClassDescription[]= [
   {
      'code' : '101',
      'name' : 'Micro services',
      'capacity': '30',
      'remaining' : 5 ,
      'location' : 'Engineering dept',
      'instructor' : 'Dr. Neha',
      'register': false 
    },
    {
       'code' : '102',
      'name' : 'Computer Science',
      'capacity': '30',
      'remaining' : 0 ,
      'location' : 'Mcarthy hall',
      'instructor' : 'Dr. Rob',
       'register': false 
     },
    {
      'code' : '103',
     'name' : 'Programming fundamental',
      'capacity': '30',
     'remaining' : 5 ,
     'location' : 'Harvard hall',
     'instructor' : 'Dr. Steven',
      'register': false 
     }
     ];


    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...