Switch Control Flow Statement
What is @switch Control Flow Statement?
@switchis a control flow statement.- It is similar to if-else, but it is used when there are many conditions.
- If there are 3–4 conditions,
if-elsecan be used. - If there are many conditions (6–7 or more),
@switchis a better option. - It improves readability and code management.
When to Use @switch?
- When multiple conditions are based on one value.
- Example scenarios:
- Many colors (10–15 colors)
- Status values like:
- notStarted
- loading
- success
- error
- Using
@switchis better than forcing multipleif-elseconditions.
Signal Used in the Code
status = signal("notStarted")
- A signal named
statusis created. - Default value is
"notStarted". - This signal can have multiple values like:
- notStarted
- loading
- success
- error
@switch Syntax Used in Template
@switch(status()){
@case('notStarted'){
<span>No update Yet</span>
}
@case('loading'){
<span style="color: orange;">loading in progress</span>
}
@case('success'){
<span style="color: green;">Success</span>
}
@default{
<span style="color: red;">Error</span>
}
}
Case Sensitivity (Common Mistake)
- Case values must exactly match the signal value.
- Capital and small letters matter.
- If values do not match, the
@defaultcase will run. - Developers often make this mistake.
Using Dropdown with @switch
<select (change)="handleSwitch($event)">
<option value="notStarted">Not Started</option>
<option value="loading">loading in progress</option>
<option value="success">success</option>
<option value="error">Error Or Other</option>
</select>
- Dropdown option values must match the switch cases.
- The change event is used to update the signal.
Change Event Handling Function
handleSwitch(event: Event){
const target = event.target as HTMLSelectElement
this.status.set(target.value)
}
- Event is received from the dropdown.
- Event target is typecast as
HTMLSelectElement. - Selected value is set in the signal.
- UI updates based on the selected value.
Output Behavior
- Default value
"notStarted"shows No update Yet. "loading"shows loading in progress."success"shows success.- Unmatched value shows error using the default case.
Styling in Example
- Inline styles are used for demonstration.
<br>tags are used for spacing.- CSS is recommended for proper spacing and styling.
Developer Mistakes Mentioned
- Using if-else when many cases exist.
- Forgetting to add
@default. - Case mismatch between signal value and case value.