I'm working on Angular. I made a checkbox list with a specific ngModel value for each checkbox.
In order to do that, I built a JSON in my TS component file. The JSON 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, here is the following "checkbox code" :
<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)
should allow me to get the name
parameter of the checkbox checked.
So in my TS file I specified ...
displayData(event: any){
console.log(event.target.name);
}
... and the console.log should get e.g "file_clocher" if I check the first checkbox.
But actually I have two problems :
Would you know how it could be corrected ?
Thank you all for your help.
You have a few issues here: the ngmodel for input is the actual value for that input field, which in the case of a checkbox is boolean. Because j.id is defined, it has a truthy value which is why they are all checked initially. You probably want another variable defined to track whether those inputs are checked.
you should be able to set the name using [name]='j.view'
or change the function to just pass in the view name with (change)="displayData(j.view)"