0

I am trying to get the values of the checkboxes that are selected. I have the following code:

<div style="background-color:lightblue;" >
    <div class="content">
       <label class="label">Province</label>
       <div class="form-check form-check-inline" *ngFor = "let province of utilities.Provinces; let i of index">    
           <label class="form-check-label" for="inlineCheckbox1" >{{province}}</label>
           <input class="form-check-input" [formControl]= "province" (change)="getSelectedProvinces()" type="checkbox" id="inlineCheckbox{{i}}" value="option1"> 
      </div>
 </div>     

In .ts I have the following

import { Component, OnInit } from '@angular/core';
import { UtilitiesService } from '../_services/utilities.service';
import { Utilities } from '../models/utilities';
import { forEach } from '@angular/router/src/utils/collection';

@Component({
selector: 'app-filtering',
templateUrl: './filtering.component.html',
styleUrls: ['./filtering.component.css']
})
export class FilteringComponent implements OnInit {
   utilities: Utilities;
   provinces:  string[] = [];
   selectedProvinces: string[] = [];
   selectedCategories: string[] = [];

   constructor(private utilityService: UtilitiesService) { }

   ngOnInit() {
     this.loadUtilities();
  }

  loadUtilities() {
    this.utilityService.getJSON().subscribe((utilities: Utilities) => {
    this.utilities = utilities;
    });

    for (const  province of this.utilities.Provinces) {
      this.provinces.push(province);
    }
  }

  getSelectedProvinces() {
      this.selectedProvinces = [];
      this.utilities.Provinces.forEach((_province, i) => {
          if (_province.value) {
          this.selectedProvinces.push(this.provinces[i]);
      }
  });
 console.log(this.selectedProvinces);
}

}

In my utilities.ts I have the following:

export interface Utilities {
  Provinces: Array<string>;
}

My service is written as follows:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Utilities } from '../models/utilities';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class UtilitiesService {

constructor(private http: HttpClient) {}

public getJSON(): Observable<Utilities> {
   return this.http.get<Utilities>('./assets/utilities.json');
}

}

The Json that is has the following content:

{
   "Provinces":["East","North West","North"]
}

When I try that, I have the following error:

TypeError: Cannot read property 'Provinces' of undefined.

The thing is, when I remove [formControl]= "province" (change)="getSelectedProvinces()", at least I am able to display the provinces on my page.

How can I go about this?

user3841581
  • 2,637
  • 11
  • 47
  • 72
  • 1
    Does this answer your question? [How to dynamically add and remove form fields in Angular 2](https://stackoverflow.com/questions/38007236/how-to-dynamically-add-and-remove-form-fields-in-angular-2) –  Jun 23 '20 at 13:17
  • I think you should be mapping your api response to Observable instead of Utilities and use that. The naming is also misleading in case of Utilities. Usually anything named in plural form should refer to a collection, not a single object – ihor.eth Jun 23 '20 at 13:23
  • @ihorbond, the problem is that I may have to add more properties to that JSON – user3841581 Jun 23 '20 at 13:35
  • Hey I solve this with cdk selectionmodel: [stackblitz](https://stackblitz.com/angular/drevrrgpaqx?file=src%2Fapp%2Ftable-selection-example.ts); [material docs](https://material.angular.io/components/table/examples) – Andre Elrico Jun 23 '20 at 16:28

1 Answers1

0

I finally solved my problem using this code below:

<div class="content">
<label class="label">Province</label>
<div class="form-check form-check-inline" *ngFor="let province of utilities.Provinces">    
    <label class="form-check-label" for="{{province}}">{{province}}</label>
    <input class="form-check-input" (change)="onChangeCategory(province, $event.target.checked)"name="{{ province}}" type="checkbox" id="{{province}}"> 
</div>

In my .ts, I have the following:

onChangeProvince(province: string, isChecked: boolean) {
   if (isChecked) {
         this.selectedProvinces.push(province);
   } else {
       const index = this.selectedProvinces.indexOf(province);
       this.selectedProvinces.splice(index, 1);
   }

 console.log(this.selectedProvinces);

}
user3841581
  • 2,637
  • 11
  • 47
  • 72