Friday, June 27, 2025

React: Just JavaScript ternary; Angular: ng-container, ngIf, else, ng-template

React:
import { useState } from 'react';
import './App.css';

function App() {
  const [theme, setTheme] = useState('light');

  return (
    <>
      <h1>React conditional rendering</h1>

      {theme === 'light' ? (
        <>
          <div>Hello Lightness</div>
          <p></p>
        </>
      ) : (
        <>
          <div>Hello Darkness</div>
          <p></p>
        </>
      )}

      <hr />
      <button onClick={toggleTheme}>Toggle Theme (current: {theme})</button>
    </>
  );

  function toggleTheme() {
    setTheme((prev) => (prev === 'light' ? 'dark' : 'light'));
  }
}

export default App;
Angular:
<h1>Angular Conditional Rendering</h1>

<ng-container *ngIf="theme === 'light'; else darkness">
  <div>Hello Lightness</div>
  <p></p>
</ng-container>

<ng-template #darkness>
  <div>Hello Darkness</div>
  <p></p>
</ng-template>

<br />
<button (click)="toggleTheme()">Toggle Theme (Current: {{theme}})</button>
import 'zone.js';
import { Component } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { CommonModule } from '@angular/common';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './main.html',
})
export class App {
  name = 'Angular';

  theme = 'light';

  toggleTheme() {
    this.theme = this.theme === 'light' ? 'dark' : 'light';
  }
}

bootstrapApplication(App);
Angular conditional renderingReact conditional rendering

No comments:

Post a Comment