Issue
I have an *ngFor
in which I am setting the values of mat-menu-item
values in order to populate a mat-menu
.
The values are set dynamically with the use of a filter.
The problem is that sometimes the the custom filter pipe doesn't return results and the mat-menu
remains empty.
...
<button mat-icon-button
matTooltip="Select alternative style"
[matMenuTriggerFor]="menu">
<mat-icon>more_vert</mat-icon>
</button>
<mat-menu #menu="matMenu">
<div *ngFor="let style of styles | filterPipe: filteredLayers[i].name">
<button mat-menu-item>
<span> {{ style.name }} </span>
</button>
</div>
</mat-menu>
...
The filterPipe
is like this
@Pipe({
name: 'filterPipe'
})
export class FilterStylePipe implements PipeTransform {
transform(styles: any[], layer: string): any {
const result = styles.filter(elem => elem.name.startsWith(layer.substring(0, 3)));
if(result.length!==0) {
return result;
}
}
}
How can i dynamically not show (or not create) themat-icon-button
or the mat-menu
?
Or even disabling it?
ADDENDUM
One possible solution is this to implement a function (menuIsNotEmpty(i)
) that returns a boolean
...
<button mat-icon-button *ngIf="menuIsNotEmpty(i)"
matTooltip="Select alternative style"
[matMenuTriggerFor]="menu">
<mat-icon>more_vert</mat-icon>
</button>
...
Whereas
menuIsNotEmpty(index) {
const result = this.styles.filter(elem => elem.name.startsWith(this.filteredLayers[index].name.substring(0, 3)));
if(result.length!==0) {
return true;
}
return false;
}
It is working but it has redundant code and the filtering is done twice to the array. I dont think that is the optimal way to do it. I m still looking on how to do it dynamically.
Solution
<ng-container *ngIf="(styles | filterPipe: filteredLayers[i].name).length > 0">
<button mat-icon-button
matTooltip="Select alternative style"
[matMenuTriggerFor]="menu">
<mat-icon>more_vert</mat-icon>
</button>
<mat-menu #menu="matMenu">
<div *ngFor="let style of styles | filterPipe: filteredLayers[i].name">
<button mat-menu-item>
<span> {{ style.name }} </span>
</button>
</div>
</mat-menu>
</ng-container>
Please double check this expression (styles | filterPipe: filteredLayers[i].name).length > 0
for null reference exception as well.
Answered By - aelagawy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.