Search code examples
htmlangularangular-material

How can set dynamically id to tag and use it in the same tag


I want to create an angular component by using mat-button-toggle-group and need to render mat-button-toggle with ngFor.

For example I set #yesterday in mat-button-toggle and use it in ngClass

<mat-button-toggle-group class="d-flex align-items-center" #group="matButtonToggleGroup" multiple (change)="toggleChange($event)">
    <mat-button-toggle value="yesterday" #yesterday [ngClass]="{'accent': yesterday.checked}">
        <span>{{ 'GENERAL_KEYS.FILTER_PARAMS.YESTERDAY' | translate }}</span>
    </mat-button-toggle>
    <mat-button-toggle value="today" #today [ngClass]="{'accent': today.checked}" checked>
        <span>{{ 'GENERAL_KEYS.FILTER_PARAMS.TODAY' | translate }}</span>
    </mat-button-toggle>
    <mat-button-toggle value="tomorrow" #tomorrow [ngClass]="{'accent': tomorrow.checked}">
        <span>{{ 'GENERAL_KEYS.FILTER_PARAMS.TOMORROW' | translate }}</span>
    </mat-button-toggle>
</mat-button-toggle-group>

How can I set id to tag and use it again?


Solution

  • You need to access the export with matButtonToggle as mentioned in the docs

    <mat-button-toggle-group name="fontStyle" aria-label="Font Style">
      <mat-button-toggle
        *ngFor="let item of toggleProps"
        [value]="item.value"
        #buttonToggle="matButtonToggle"
        [ngClass]="{'accent': buttonToggle.checked}"
        >{{item.label}}</mat-button-toggle
      >
    </mat-button-toggle-group>
    

    TS:

    import { CommonModule } from '@angular/common';
    import { Component } from '@angular/core';
    import { MatButtonToggleModule } from '@angular/material/button-toggle';
    
    /**
     * @title Basic button-toggles
     */
    @Component({
      selector: 'button-toggle-overview-example',
      templateUrl: 'button-toggle-overview-example.html',
      standalone: true,
      styles: [
        `
      ::ng-deep .accent {
        background-color: red !important;
      }
      `,
      ],
      imports: [MatButtonToggleModule, CommonModule],
    })
    export class ButtonToggleOverviewExample {
      toggleProps: any = [
        { value: 'bold', label: 'Bold' },
        { value: 'italic', label: 'Italic' },
        { value: 'underline', label: 'Underline' },
      ];
    }
    

    Stackblitz Demo