SomeStudent
SomeStudent

Reputation: 3048

Angular mat-checkbox for attribute not working

I am trying to tie my label to the checkbox, so that the user can select the label to trigger the checkbox, instead of just being limited to clicking the checkbox. I know that in good ol' ASP.NET MVC I would just use something like LabelFor.

Here, it seems to not work; I've looked at other SO posts, along with the following post on github https://github.com/angular/angular/issues/5435. The above did not do it, though looking at the HTML I can see that two changes happen to its DOM, one which seems to actually trigger it, then it reverts back to the unclicked stage. The (change) method on the checkbox itself does not get fired.

Here is my code:

<ul>
    <li formArrayName="EntryTypes" *ngFor="let t of filterOptions; let i = index"
                    fxLayout="row" fxLayoutAlign="start start" fxLayoutGap="40px" [ngClass]="{'checked' : isChecked}">
        <mat-checkbox [id]="'mat-checkbox-'+ i +'-input'" [formControlName]="i" (change)="onCheckChange($event, i)">
            <label [attr.for]="'mat-checkbox-'+ i +'-input'">{{t}}</label>
        </mat-checkbox>
    </li>
</ul>

I've manually applied the id attribute to each checkbox, as otherwise it won't actually be a guarantee that its ID is synced up with the index. Ex: The first element, may have an id of mat-checkbox-3-input even though it is the first element and thus should have an index of 0.

Am I missing something seriously obvious here? I know I could just add a click function on the label and call it a day, but why reinvent the wheel when there is a handy for attribute

Upvotes: 0

Views: 999

Answers (1)

SomeStudent
SomeStudent

Reputation: 3048

Not quite sure how this is different from the original html, but this html seems to do it:

<li formArrayName="EntryTypes" *ngFor="let t of filterOptions; let i = index"
                    fxLayout="row" fxLayoutAlign="start start" fxLayoutGap="40px" [ngClass]="{'checked' : isChecked}">
                    <mat-checkbox id={{i}} [formControlName]="i" (change)="onCheckChange($event, i)">
                        <label [attr.for]="i+'-input'">{{t}}</label>
                    </mat-checkbox>
                </li>

Only thing I see different is using id instead of [id]

Upvotes: 1

Related Questions