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" ></label>
<input class="form-check-input" [formControl]= "province" (change)="getSelectedProvinces()" type="checkbox" id="inlineCheckbox" 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?
Aucun commentaire:
Enregistrer un commentaire