Performance: *ngIf for conditional rendering
Controls whether elements are added or removed from the DOM, impacting initial load and interaction speed.
<div *ngIf="isVisible">Content</div><div [hidden]="!isVisible">Content</div>| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| [hidden] binding | No DOM changes | 0 on toggle | Low but persistent | [!] OK |
| *ngIf directive | Adds/removes nodes | 1 per toggle | Moderate on toggle | [OK] Good |
*ngIf do in a template?*ngIf*ngIf is used to conditionally render elements in Angular templates.*ngIf controlsisVisible is true?*ngIf with an asterisk to indicate a structural directive.*ngIf=, like *ngIf="isVisible".<div *ngIf="showMessage">Welcome!</div> <button (click)="showMessage = !showMessage">Toggle</button>
showMessage = true?showMessage is true, so the <div> with 'Welcome!' is shown. Clicking the button toggles showMessage between true and false.showMessage to false, hiding the message. Second click sets it back to true, showing the message again.<div *ngIf="user.isLoggedIn">Hello, {{user.name}}!</div>Cannot read property 'isLoggedIn' of undefined. What is the best fix?user is undefined when Angular tries to read user.isLoggedIn.user?.isLoggedIn prevents error by checking if user exists before accessing isLoggedIn.email property and is verified (isVerified true). Which *ngIf expression correctly handles this?user.email is not empty (truthy) AND user.isVerified is true.*ngIf="user.email && user.isVerified" uses logical AND to require both conditions true. *ngIf="user.email || user.isVerified" uses OR, which is incorrect. *ngIf="user.email == '' && user.isVerified" checks for empty string which is opposite of requirement. *ngIf="user.email.length > 0 || user.isVerified" uses OR and length check but allows message if only one condition is true.Pass the test and this pattern moves unknown