Concept Flow - *ngIf for conditional rendering
Start
Evaluate *ngIf condition
Render element in DOM
Do not render element
End
Angular checks the *ngIf condition. If true, it adds the element to the page. If false, it removes or skips it.
<div *ngIf="showMessage">Hello, Angular!</div> <button (click)="toggle()">Toggle Message</button> showMessage = true; toggle() { this.showMessage = !this.showMessage; }
| Step | Action | *ngIf Condition (showMessage) | Render Element? | DOM Change |
|---|---|---|---|---|
| 1 | Initial render | true | Yes | Element <div>Hello, Angular!</div> added to DOM |
| 2 | User clicks button | true -> false | No | Element removed from DOM |
| 3 | User clicks button again | false -> true | Yes | Element added back to DOM |
| 4 | No further clicks | true | Yes | No change |
| Exit | No more actions | - | - | Rendering stable |
| Variable | Start | After 1 | After 2 | After 3 | Final |
|---|---|---|---|---|---|
| showMessage | true | false | true | true | true |
*ngIf directive conditionally adds or removes elements from the DOM. Syntax: <element *ngIf="condition">content</element> If condition is true, element is rendered. If false, element is removed completely. Useful for showing/hiding UI based on variables.
*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