Bird
0
0

You want to conditionally add a CSS class to a list item only if it is visible, and also only render visible items. Which is the best way to combine structural and attribute directives?

hard📝 component behavior Q8 of 15
Angular - Directives
You want to conditionally add a CSS class to a list item only if it is visible, and also only render visible items. Which is the best way to combine structural and attribute directives?
A<ng-container *ngFor="let item of items"><li *ngIf="item.visible" [ngClass]="{visible: item.visible}">{{item.name}}</li></ng-container>
B<li *ngFor="let item of items" [ngClass]="{visible: item.visible}" *ngIf="item.visible">{{item.name}}</li>
C<li *ngFor="let item of items" *ngIf="item.visible" [ngClass]="{visible: item.visible}">{{item.name}}</li>
D<li [ngFor]="items" *ngIf="item.visible" [ngClass]="{visible: item.visible}">{{item.name}}</li>
Step-by-Step Solution
Solution:
  1. Step 1: Recall structural directive rules

    Only one structural directive per element is allowed.
  2. Step 2: Use <ng-container> to separate directives

    Wrapping *ngFor on <ng-container> and *ngIf on <li> allows both directives without conflict.
  3. Final Answer:

    <ng-container *ngFor=\"let item of items\"><li *ngIf=\"item.visible\" [ngClass]=\"{visible: item.visible}\">{{item.name}}</li></ng-container> -> Option A
  4. Quick Check:

    Use ng-container to separate multiple structural directives [OK]
Quick Trick: Use ng-container to apply multiple structural directives [OK]
Common Mistakes:
  • Applying two * directives on same element
  • Using [ngFor] instead of *ngFor

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes