I am currently developing an application using Angular. I have created a checkbox list where each checkbox has a specific ngModel value assigned to it.
To achieve this, I have defined a JSON object in my TypeScript component file which looks like this :
test = [
{id: 'model1', site: '1', label: 'Clocher', view: 'file_clocher'},
{id: 'model2', site: '1', label: 'Moulin', view: 'file_moulin'},
{id: 'model3', site: '1', label: 'Poisson', view: 'file_poisson'},
{id: 'model4', site: '2', label: 'Lacs', view: 'file_lac'},
{id: 'model5', site: '2', label: 'Relais', view: 'file_relais'},
{id: 'model6', site: '3', label: 'Citadelle', view: 'file_citadelle'},
]
In the HTML file, below is the code for the checkboxes:
<div *ngFor="let j of test">
<div *ngIf="j.site == '1'" class="form-check">
<input class="form-check-input" type="checkbox" [(ngModel)]="j.id" (change)="displayData($event)" name="{{j.view}}"/>
<label class="form-check-label">{{j.label}}</label>
</div>
</div>
The displayData($event)
function is meant to retrieve the name
parameter of the checked checkbox.
Therefore, in my TypeScript file, I have implemented...
displayData(event: any){
console.log(event.target.name);
}
... and upon checking the first checkbox, the console should log e.g "file_clocher".
However, there are two issues I am facing:
- All the checkboxes appear to be pre-checked, which is unexpected
- When selecting the first checkbox, the console outputs "undefined" instead of the expected value such as "file_clocher" (manual testing without JSON data works fine)
If you have any suggestions on how to rectify these problems, I would greatly appreciate your assistance.
Thank you in advance for your support.