Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make aria-selected true on selected tab on click in Angular

I am building a reusable navigation "tabs" component where I would like the selected tab to be set to "true" for aria-selected on click, however aria-selected is remaining false for all three tabs on click. How do I set an individual tab to true if it is clicked?

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  tabs = [
    { tabName: 'tab1' },
    { tabName: 'tab2' },
    { tabName: 'tab3' }
  ]
  selected: boolean;

  select(tab){
    this.selected = tab.tabName
  }
}

app.component.html

<div role="tablist">
  <app-tabs 
  *ngFor="let tab of tabs" 
  (click)="select(tab)"
  [selected]="selected" 
  [tab]="tab">
  </app-tabs>
</div>

tabs.component.ts

import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-tabs',
  templateUrl: './tabs.component.html',
  styleUrls: ['./tabs.component.css']
})
export class TabsComponent implements OnInit {

  @Input() tab
  @Input() selected

}

tabs.component.html

<span 
role="tab" 
(click)="handleSelected($event)" 
aria-selected="tab.tabName === selected">
  {{tab.tabName}}
</span>
like image 299
FakeEmpire Avatar asked Nov 16 '25 12:11

FakeEmpire


1 Answers

Use [attr.aria-selected]="tab.tabName === selected" instead of aria-selected="tab.tabName === selected". The former is binding to a property of the component class, the later is just passing the literal value

like image 142
Armen Vardanyan Avatar answered Nov 18 '25 07:11

Armen Vardanyan