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?

4
  • 1
    Does this answer your question? How to dynamically add and remove form fields in Angular 2 Commented Jun 23, 2020 at 13:17
  • I think you should be mapping your api response to Observable<Provinces[]> 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 Commented Jun 23, 2020 at 13:23
  • @ihorbond, the problem is that I may have to add more properties to that JSON Commented Jun 23, 2020 at 13:35
  • Hey I solve this with cdk selectionmodel: stackblitz; material docs Commented Jun 23, 2020 at 16:28

1 Answer 1

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);

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.