Crafting interactive buttons with angular material

I've been working on an angular application where I created 5 mat flat buttons using angular material.

<button mat-flat-button [ngClass]="this.selected == 1 ? 'tab_selected' : 'tab_unselected'" (click)="change(1)">B-L1</button>
<button mat-flat-button [ngClass]="this.selected == 2 ? 'tab_selected' : 'tab_unselected'" (click)="change(2)">B-L2</button>
<button mat-flat-button [ngClass]="this.selected == 3 ? 'tab_selected' : 'tab_unselected'" (click)="change(3)">B-L3</button>
<button mat-flat-button [ngClass]="this.selected == 4 ? 'tab_selected' : 'tab_unselected'" (click)="change(4)">B-L4</button>
<button mat-flat-button [ngClass]="this.selected == 5 ? 'tab_selected' : 'tab_unselected'" (click)="change(5)">B-FC</button>

Each button triggers a function in the .ts file when clicked.

change(n) {
    this.selected = n;
    if (n == 3){
      this.floor = 'BL3'
    }
    else if (n==4){
      this.floor  = 'BL4'
    }
    else if (n==2){
      this.floor  = 'BL2'
    }
    else if(n==1){
      this.floor  = 'BL1'
    }
    else if(n==5){
      this.floor  = 'BFC'
    }

    console.log('changing floor to' + this.floor)
    this.getData(this.floor)
}

this.getData(this.floor) triggers an API call to retrieve data for that specific floor. The blocks are represented by B and the floors within each block are L1, L2, L3, etc.

I now need to add a new block D with floors L1, L2, L3, and L4. Instead of manually adding more buttons for DL1, DL2, DL3, how can I dynamically display them based on selecting either the B or D master button while maintaining the current functionality?

Any suggestions would be greatly appreciated. Thank you!

Answer №1

see the code in action

Insert the following code snippet into the component file:

selectedItem:any;
floorSelectedItem:any;
buildingBlock:any;

changeBuildingBlock(block){
   if(block){
     this.buildingBlock = block;
   }
 }

selectFloor(floor, block){
  if(floor){
    this.selectedItem = floor;
    this.floorSelectedItem = block+'L'+floor;
  }
  console.log( this.floorSelectedItem );
}

Update the HTML page with the following changes:

<div>
   <button mat-flat-button [ngClass]="this.selected == i ? 'tab_selected' : 'tab_unselected'" (click)="changeBuildingBlock('B')">B</button>
   <button mat-flat-button [ngClass]="this.selected == i ? 'tab_selected' : 'tab_unselected'" (click)="changeBuildingBlock('D')">D</button>
</div>

<div *ngIf="buildingBlock">
   <div *ngFor="let i of [1,2,3,4,5]" >
      <button mat-flat-button [ngClass]="this.selected == i ? 'tab_selected' : 'tab_unselected'" (click)="selectFloor(i, buildingBlock)">{{buildingBlock}}-L{{i}}</button>
   </div>
</div>

Answer №2

Check out this live demo

  <button md-raised-button *ngFor="let item of myButtons; let i = index" 
          (click)="updateActive(i)" #disable>{{item.name}} Basic</button>

.ts

    myButtons = [
    { name: 'Button A' },
    { name: 'Button B' },
    { name: 'Button C' }
  ];

  lastSelectedIndex;
  updateActive(i) {
    console.log("clicked ",i)
    this.lastSelectedIndex = i;
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Drizzle ORM retrieve unique string that is not a database column

I'm working with a SQL query that looks like this: SELECT * FROM ( SELECT 'car' AS type, model FROM car UNION SELECT 'truck' AS type, model FROM trucks ) vehicles; In Drizzle, I'm trying to replicate the 'car ...

Mastering the art of duplicating an array of objects in TypeScript

I attempted the following strategy: this.strategies = []; this.strategiesCopy = [...this.strategies]; Unfortunately, it appears this method is not effective as it results in duplicates. ...

The program experienced an issue with TypeError: Attempting to access properties of an undefined variable ('_id')

I am attempting to show a data entry (with a unique id) in Angular, but I'm encountering the following error: ERROR TypeError: Cannot read properties of undefined (reading '_id') The service for retrieving the specific id is defined as: g ...

Is it possible for a Node.js/Express server to securely handle all UTF-8 characters?

At the moment, my setup involves a node server running Express that is connected to a PostgreSQL database with UTF-8 encoding support. In terms of frontend, I'm using Angular which has built-in measures for preventing unsafe injection. I am curious i ...

Can a decorator be added to a Typescript class after it has been created?

Is it possible to update a class with inversify's @injectable decorator after it has been created? My use case involves using a mocking library like ts-auto-mock to generate a mock for me, and then applying the @injectable decorator to bind the mock t ...

What is the process for running a continuous stream listener in a node.js function?

I am currently working with a file called stream.ts: require('envkey') import Twitter from 'twitter-lite'; const mainFn = async () => { const client = new Twitter({ consumer_key: process.env['TWITTER_CONSUMER_KEY'], ...

converting an angular object into a string representation

I stumbled upon this guide: . and it includes the following piece of code: import { Component } from '@angular/core'; import { FormGroup, FormControl } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl ...

There is an issue with the property 'updateModf' in the constructor as it does not have an initializer and is not definitely assigned

When working with an angular reactive form, I encountered an issue. After declaring a variable with the type FormGroup like this: updateModf:FormGroup; , the IDE displayed an error message: Property 'updateModf' has no initializer and is not def ...

Alert: The route "/D:/original/22-02-2017/job2.html" specified in [react-router] does not correspond to any existing routes

I am currently working on a project using TypeScript with React. I'm utilizing webpack as a compiler, and my directory structure looks like this: d:/original/22-02-2017/ - In my web.config.js file, the entry point is set to ./src/index.tsx. All ...

Having trouble personalizing the background color according to the ItemName in angular2-multiselect-dropdown

Is it possible to customize the background color in angular2-multiselect-dropdown based on the tags label? I want the background color to be determined by the tags label. The npm package provides no description regarding this feature here https://i.ssta ...

Surprising Discovery: TypeScript - node_modules Found in Unusual Directory

Is there a way to make TypeScript imports function properly even if the node_modules directory is not directly in the tree? How can I prevent TypeScript from throwing errors when importing something like rxjs from external/node_modules. For Example: Dir ...

Is it possible to set up VS Code's code completion feature to automatically accept punctuation suggestions?

For all the C# devs transitioning to TypeScript in VS Code, this question is directed at you. I was captivated by the code completion feature in VS C#. To paint a clearer picture, let's say I'm trying to write: console.log('hello') W ...

Is it possible to create a child route with parameters that point to components within a lazily-loaded module?

Here is my app.routing.module setup: { path: 'dashboard', component: DashboardComponent }, { path: 'reports', loadChildren: () => import('./reports/reports.module').then(m => m.ReportsModule) The routes for the lazy-loa ...

Can you use the useCallback function within a nested callback function?

within component A: const retrieveOnClick = useCallback( (rec: GenericRec): (() => void) => () => { setSelectedRecord(rec); }, [], ); inside component B which is a child of A: const displayRecord = useCallback( (row: Row& ...

Error encountered when using Angular Material date-time picker

I encountered an error in the console when trying to use the Angular Material datetime picker. Although it functions correctly, my tests failed due to this error. https://www.npmjs.com/package/@angular-material-components/datetime-picker <mat-form-fiel ...

How to make an HTTP request in Angular 7 before the browser is closed

I'm attempting to trigger a POST HTTP request right before the browser closes. Essentially, I want to detect when the user closes the page and send a call, but the request isn't completing before shutdown. It seems like a traditional HTTP reque ...

Sorting through a JavaScript array

I am facing a peculiar problem while trying to filter an array in TypeScript. Here is the structure of my object: Sigma.model.ts export class Sigma { sigmaId: number; name: string; userId: number; starId: string; } `` The starId property contains com ...

Unable to personalize map controls in OpenLayer mapping system

Having trouble styling custom map controls with CSS selectors .ol-zoom-in and .ol-zoom-out. Any suggestions on how to customize them? export class CustomMapControlsComponent implements OnInit { map: Map | undefined; constructor() {} ngOnInit() ...

Display the Slug in the Website URL upon clicking on a Blog Post using Angular and Strapi framework

When a user clicks on a blog, I want the URL to display the slug instead of the ID. My frontend framework is Angular and I have created a service to fetch data from the backend built with Strapi. Currently, when selecting a blog from the view, the URL disp ...

One function in Typescript lodash is missing a default export

Is there a way to import just one function from lodash? I attempted it like this: import get from 'lodash/get'; Even after installing both lodash and @types/lodash, I encountered the following error message: @types/lodash/get/index"' ha ...