user2872470
user2872470

Reputation:

ngIf to find substr

       <ul class="list-group" *ngFor="let head of channelDisplayHeads">
        <li class="list-group-item" *ngFor="let channel of channelList" ngIf="channel.channel.indexOf('head') === 1">
          <strong>{{ head }}</strong>
        </li>
      </ul>

Here the ngFor loop displays group heads like "A", "B", "C" etc. For each group head I am trying to list the channels starting with that letter in which the for loop is in. I am trying to accomplish this behavior using ngIf, but it doesn't seem to work as expected. Please advise!

Upvotes: 0

Views: 5012

Answers (4)

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41447

ngIf and ngFor on the same element isn't supported. use ngIf inside template

<ul class="list-group" *ngFor="let head of channelDisplayHeads">
    <h1>{{ head }}</h1>
    <ng-container *ngFor="let channel of channelList">
        <li class="list-group-item" *ngIf="channel.channel.substr(0, 1) === head"> <strong></strong> <strong>{{ channel.channel }} </strong> </li>
    </ng-container>
</ul>

Upvotes: 1

user2872470
user2872470

Reputation:

Finally this code worked as expected

 <ul class="list-group" *ngFor="let head of channelDisplayHeads">
                <h1>{{ head }}</h1>
                <ng-container *ngFor="let channel of channelList">
                  <li class="list-group-item" *ngIf="channel.channel.substr(0, 1) === head">
                    <strong></strong>
                    <strong>{{ channel.channel }} </strong>
                  </li>
                </ng-container>
              </ul>

Upvotes: 2

Suraj Rao
Suraj Rao

Reputation: 29625

There are a number of issues here.

  1. Your syntax for ngIf is incorrect. It needs to be *ngIf.
  2. You cannot have both *ngFor and *ngIf on the same element. Use ng-container for one of them. This is angular's element which will not be rendered in the html and is only for angular directives.
  3. You seem to be passing the head variable as a string. If you want to check for the element, remove the quotes.

     <ul class="list-group" *ngFor="let head of channelDisplayHeads">
       <ng-container *ngFor="let channel of channelList">
         <li class="list-group-item" *ngIf="channel.channel.indexOf(head) === 1">
            <strong>{{ head }}</strong>
         </li>
       </ng-container>
     </ul>
    

Upvotes: 2

Pranay Rana
Pranay Rana

Reputation: 176936

your forgot * here , please include it as given below and try it out,

 *ngIf="channel.channel.indexOf('head') === 1"

Following is working for me

template

   <ul *ngFor="let hero of numbers"  >  
   <div *ngIf="hero==1">
   {{hero}}
   </div>
   </ul>

ts file

  numbers: Array<string> = new Array<string>();
  constructor()
  {
    this.numbers.push('1');
    this.numbers.push('2');
    this.numbers.push('3');
  }

Upvotes: 1

Related Questions