Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Change active tabs (Typescript)

I have array of tabs.

Here is the code

const navTabs: ITab[] = [
    { Name: allTab, Icon: 'gs-all', Selected: true },
    { Name: sources.corporateResources, Icon: 'gs-resources', Selected: false },
    { Name: sources.employee, Icon: 'gs-people', Selected: false },
    { Name: sources.services, Icon: 'gs-services', Selected: false },
    { Name: sources.information, Icon: 'gs-docs', Selected: false },
    { Name: sources.tableau, Icon: 'gs-tableau', Selected: false },
];

In method activate tab I change selected: true tab to false and than I find tab by name and set it to selected: true

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here is code

public activateTab(name: TabName): void {
    this.activeTab = name;
    this.navTabs.find(x => x.Selected === true).Selected = false;
    this.navTabs.find(x => x.Name === name).Selected = true;
    // console.log(navTabs);
}

Can I make somehow this in one operation?

this.navTabs.find(x => x.Selected === true).Selected = false;
this.navTabs.find(x => x.Name === name).Selected = true;

>Solution :

You could loop over them all (forEach) and then set Selected to the condition where you check the name:

const navTabs = [
  { Name: 'foo', Icon: 'gs-all', Selected: true },
  { Name: 'foo', Icon: 'gs-resources', Selected: false },
  { Name: 'foo', Icon: 'gs-people', Selected: false },
  { Name: 'bar', Icon: 'gs-services', Selected: false },
  { Name: 'foo', Icon: 'gs-docs', Selected: false },
  { Name: 'foo', Icon: 'gs-tableau', Selected: false },
];

const nameToMatch = 'bar';

navTabs.forEach(o => o.Selected = (o.Name === nameToMatch));

console.log(navTabs);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading