Search code examples
angularngforangular-ng-if

*ngIf inside *ngfor to validate each item of the for loop


<li *ngFor="let year of paper?.years" class="list-group-item">                                                
                    <div>
                        <a routerLink="/viewpdf/{{year.questionPaper.fileId}}">Question Paper - {{year.formattedYear }}</a> 
                        <a href="{{ downloadUrl }}/{{year.questionPaper.fileId}}" class="fa fa-download" aria-hidden="true"></a>
                    </div>
                    <div> 
                        <a routerLink="/viewpdf/{{year.markScheme.fileId}}"> || Mark Scheme - {{year.formattedYear }}</a>                        
                        <a href="{{ downloadUrl }}/{{year.markScheme.fileId}}" class="fa fa-download" aria-hidden="true"></a>
                    </div>   
</li>

The above code is working fine. But I want to check each fileId, if its null or not. If null then the links will not generate and vice versa.

I have setted *ngIf, below is a code sample. But its not working.

<li *ngFor="let year1 of paper?.years" class="list-group-item">  

                    <div *ngif="year.questionPaper.fileId != ''">
                        <a routerLink="/viewpdf/{{year.questionPaper.fileId}}">Question Paper - {{year.formattedYear }}</a> 
                        <a href="{{ downloadUrl }}/{{year.questionPaper.fileId}}" class="fa fa-download" aria-hidden="true"></a>
                    </div>
                    <div *ngif="year.markScheme.fileId != ''"> 
                        <a routerLink="/viewpdf/{{year.markScheme.fileId}}"> || Mark Scheme - {{year.formattedYear }}</a>                        
                        <a href="{{ downloadUrl }}/{{year.markScheme.fileId}}" class="fa fa-download" aria-hidden="true"></a>
                    </div>                      

                </li>

I have tried several other ways, but nothing is working. Like : defining ng-template.


Solution

  • No need to use == or !=.

    Just modify your code with the below code.

    <li *ngFor="let year1 of paper?.years" class="list-group-item">      
         <div *ngIf="year.questionPaper.fileId">
            <a routerLink="/viewpdf/{{year.questionPaper.fileId}}">Question Paper - {{year.formattedYear }}</a> 
            <a href="{{ downloadUrl }}/{{year.questionPaper.fileId}}" class="fa fa-download" aria-hidden="true"></a>
         </div>
         <div *ngIf="year.markScheme.fileId"> 
            <a routerLink="/viewpdf/{{year.markScheme.fileId}}"> || Mark Scheme - {{year.formattedYear }}</a>                        
            <a href="{{ downloadUrl }}/{{year.markScheme.fileId}}" class="fa fa-download" aria-hidden="true"></a>
        </div>                        
    </li>
    

    Explanation:

    <div *ngIf="year.questionPaper.fileId"> // This will automatically check for null, undefined and empty string.