How to declare ngif value by concatenate in angular

Viewed 54

Trying to hide bullet point by ngIf but not working. How to declare an ngif value by concatenating If anyone knows, please help to find the solution.

app.component.html:

<mat-list>
    <mat-list-item *ngFor="let season of seasons; index as i">
        <span *ngIf="season.toLowerCase().split(' ').join('') + i" class="bullet"></span>
        <p (click)="hides(season)" matLine>{{ season }}</p>
    </mat-list-item>
</mat-list>

Demo : https://stackblitz.com/edit/angular-8-material-starter-template-uewc3u?file=src%2Fapp%2Fapp.component.html

3 Answers

I try to modify your data seasons and become like this

for app.component.html

<mat-list>
  <mat-list-item *ngFor="let season of seasons; index as i">
    <span class="bullet" *ngIf="season.bullet"></span>
    <p matLine (click)="hides(season)">{{ season.title }}</p>
  </mat-list-item>
</mat-list>

for app.component.ts

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

export interface Season {
  title: string;
  bullet: boolean;
}

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  name = 'Angular';
  seasons: any[] = [
    { title: 'Group id', bullet: true },
    { title: 'Group name', bullet: true },
    { title: 'Group value', bullet: true },
  ];

  constructor() {}
  ngOnInit() {}

  hides(val: any) {
    const index = this.seasons.findIndex((item) => item.title === val.title);
    val.bullet
      ? (this.seasons[index]['bullet'] = false)
      : (this.seasons[index]['bullet'] = true);
  }
}

More detail https://stackblitz.com/edit/angular-8-material-starter-template-pa4aus?file=src/app/app.component.html

You can't use ngIf like that in angular. Instead you can define a getter:

component.ts

class YourComponent {
    private _seasons: string[] = [ /* original seasons array */ ]

    public get seasons() {
        return this._seasons.map((s, i) => ({
            _original: s,
            get condition() {
                return this._original
                    .toLowerCase()
                    .split(' ')
                    .join('') + i
            }
        }))
    }
}

and component.html

<mat-list>
    <mat-list-item *ngFor="let season of seasons">
        <span *ngIf="season.condition" class="bullet"></span>
        <p (click)="hides(season)" matLine>{{ season }}</p>
    </mat-list-item>
</mat-list>
Related