*ngIf and *ngFor on same element causing error

后端 未结 16 2069
自闭症患者
自闭症患者 2020-11-22 02:37

I\'m having a problem with trying to use Angular\'s *ngFor and *ngIf on the same element.

When trying to loop through the collection in th

相关标签:
16条回答
  • 2020-11-22 03:09

    You can do this another way by checking the array length

    <div *ngIf="stuff.length>0">
      <div *ngFor="let thing of stuff">
        {{log(thing)}}
        <span>{{thing.name}}</span>
      </div>
    </div>
    
    0 讨论(0)
  • 2020-11-22 03:10

    <!-- Since angular2 stable release multiple directives are not supported on a single element(from the docs) still you can use it like below -->
    
    
    <ul class="list-group">
                    <template ngFor let-item [ngForOf]="stuff" [ngForTrackBy]="trackBy_stuff">
                        <li *ngIf="item.name" class="list-group-item">{{item.name}}</li>
                    </template>
       </ul>

    0 讨论(0)
  • 2020-11-22 03:11

    in html:

    <div [ngClass]="{'disabled-field': !show}" *ngFor="let thing of stuff">
        {{thing.name}}
    </div>
    

    in css:

    .disabled-field {
        pointer-events: none;
        display: none;
    }
    
    0 讨论(0)
  • 2020-11-22 03:13

    You can also use ng-template (instead of template. See the note for the caveat of using template tag) for applying both *ngFor and ngIf on the same HTML element. Here is an example where you can use both *ngIf and *ngFor for the same tr element in the angular table.

    <tr *ngFor = "let fruit of fruiArray">
        <ng-template [ngIf] = "fruit=='apple'>
            <td> I love apples!</td>
        </ng-template>
    </tr>
    

    where fruiArray = ['apple', 'banana', 'mango', 'pineapple'].

    Note:

    The caveat of using just the template tag instead of ng-template tag is that it throws StaticInjectionError in some places.

    0 讨论(0)
提交回复
热议问题