Switch Control Flow Statement

What is @switch Control Flow Statement?

  1. @switch is a control flow statement.
  2. It is similar to if-else, but it is used when there are many conditions.
  3. If there are 3–4 conditions, if-else can be used.
  4. If there are many conditions (6–7 or more), @switch is a better option.
  5. It improves readability and code management.


When to Use @switch?

  1. When multiple conditions are based on one value.
  2. Example scenarios:
  3. Many colors (10–15 colors)
  4. Status values like:
  5. notStarted
  6. loading
  7. success
  8. error
  9. Using @switch is better than forcing multiple if-else conditions.


Signal Used in the Code

status = signal("notStarted")
  1. A signal named status is created.
  2. Default value is "notStarted".
  3. This signal can have multiple values like:
  4. notStarted
  5. loading
  6. success
  7. 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)

  1. Case values must exactly match the signal value.
  2. Capital and small letters matter.
  3. If values do not match, the @default case will run.
  4. 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>
  1. Dropdown option values must match the switch cases.
  2. 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)
}
  1. Event is received from the dropdown.
  2. Event target is typecast as HTMLSelectElement.
  3. Selected value is set in the signal.
  4. UI updates based on the selected value.


Output Behavior

  1. Default value "notStarted" shows No update Yet.
  2. "loading" shows loading in progress.
  3. "success" shows success.
  4. Unmatched value shows error using the default case.


Styling in Example

  1. Inline styles are used for demonstration.
  2. <br> tags are used for spacing.
  3. CSS is recommended for proper spacing and styling.


Developer Mistakes Mentioned

  1. Using if-else when many cases exist.
  2. Forgetting to add @default.
  3. Case mismatch between signal value and case value.