Issue
I am creating a seating plan using the mat-grid-list component for creating some cells. I need that, once I clicked on a specific cell a mat icon appears, and when I click the same cell again it disappear.
I tried this. In my DOM:
<mat-grid-list [cols]="numColumns" id="container">
<div *ngFor="let row of rows">
<mat-grid-tile *ngFor="let col of cells" (click)="onCellClick($event)"
(dblclick)="onRename($event)" (contextmenu)="onRightClick($event)">
<mat-icon>{{icon}}</mat-icon>
</mat-grid-tile>
</div>
</mat-grid-list>
In my Typescript, the onCellClick function is strucured this way:
public icon!: string;
/** Colors a cell depending on the selected icon */
onCellClick(ev: any) {
this.curr_cell = ev.target;
if (this.regularSeatIconSelected === true) {
this.curr_cell.value = 'Regular Seat';
if (this.curr_cell.style.backgroundColor !== 'green') {
this.curr_cell.style.backgroundColor = 'green';
this.icon = 'event_seat';
} else {
this.curr_cell.style.backgroundColor = '';
this.curr_cell.value = '';
this.icon = '';
}
}
The problem with this code, is that when i click on a cell, every cell in the grid-list is updated with this new icon. How can i add the icon for a specific cell? If you have any suggestion please let me know. Thank you! :)
Solution
You need to create a 2d Array of values, and maintain a local property called selected
in each of the elements, but for simplicity purposes, please find below the code, that will toggle the class through javascript. Ideally you should use the first option.
import { Component, ElementRef } from '@angular/core';
import { MatGridTile, MatIcon } from '@angular/material';
/**
* @title Basic icons
*/
@Component({
selector: 'icon-overview-example',
templateUrl: 'icon-overview-example.html',
styleUrls: ['icon-overview-example.css'],
})
export class IconOverviewExample {
numColumns = 5;
rows = [1, 2, 3, 4, 5];
cells = [1, 2, 3, 4, 5];
regularSeatIconSelected = true;
onCellClick(ev: any) {
console.log(ev.target);
const curr_cell = ev.target.classList.contains('mat-icon')
? ev.target.parentElement
: ev.target;
const icon = ev.target.querySelector('.mat-icon') || ev.target;
console.log(curr_cell);
if (this.regularSeatIconSelected) {
curr_cell.value = 'Regular Seat';
if (curr_cell.style.backgroundColor !== 'green') {
curr_cell.style.backgroundColor = 'green';
icon.innerText = 'event_seat';
} else {
curr_cell.style.backgroundColor = '';
curr_cell.value = '';
icon.innerText = '';
}
}
}
}
Answered By - Naren Murali
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.