Angular Quick Fixes: Conditional Rendering and Data Binding
This challenge focuses on implementing common Angular patterns for dynamic user interfaces: conditional rendering based on application state and updating the UI with data binding. You will create a simple component that displays different messages and UI elements based on a user's logged-in status. This is a fundamental skill for building interactive Angular applications.
Problem Description
Your task is to create an Angular component that conditionally displays a welcome message and an action button.
Requirements:
- Component Creation: Create a new Angular component named
AuthStatusDisplayComponent. - Input Property: The component should accept an input property named
isLoggedInof typeboolean. - Conditional Rendering:
- If
isLoggedInistrue, the component should display "Welcome back, User!" and a button with the text "Logout". - If
isLoggedInisfalse, the component should display "Please log in to continue." and a button with the text "Login".
- If
- Data Binding: The text of the buttons should be dynamically bound to the state of the
isLoggedInproperty. - Event Handling (Optional but recommended): For a more complete example, implement a placeholder
clickevent handler for the buttons that logs a message to the console (e.g., "Login clicked" or "Logout clicked"). This demonstrates event binding.
Expected Behavior:
When the isLoggedIn input property changes, the component's template should update accordingly to show the correct message and button.
Edge Cases:
- The initial state of
isLoggedIn(eithertrueorfalse) should be handled correctly.
Examples
Example 1:
Input to the component: isLoggedIn = true
Output in the browser:
<p>Welcome back, User!</p>
<button>Logout</button>
Explanation: Since isLoggedIn is true, the "Welcome back" message and the "Logout" button are displayed.
Example 2:
Input to the component: isLoggedIn = false
Output in the browser:
<p>Please log in to continue.</p>
<button>Login</button>
Explanation: Since isLoggedIn is false, the "Please log in" message and the "Login" button are displayed.
Constraints
- The solution must be implemented in TypeScript using Angular.
- Use Angular's built-in directives for conditional rendering (e.g.,
*ngIf). - Use Angular's data binding syntax for button text.
- The component should be a standalone component or part of a module as per your project setup.
Notes
- Consider using
*ngIfand*ngIf elsefor cleaner conditional rendering. - You can simulate changes to the
isLoggedInproperty by using a parent component that passes different values toAuthStatusDisplayComponent. - For the optional event handling, you can use
(click)="onButtonClick()"in your template and define anonButtonClick()method in your component class.