Skip to content

Let's recreate the "Magical Users" app in Angular. As we go along, I'll explain each Angular concept in-depth, and contrast it with the React approach from the given exercise. #161

Description

@imwirelesscloud

Let's recreate the "Magical Users" app in Angular. As we go along, I'll explain each Angular concept in-depth, and contrast it with the React approach from the given exercise.

Creating "Magical Users" App in Angular

Step 1: Setup

  1. React: Initialized the React app using Create React App.
  2. Angular: Initialize a new Angular app using Angular CLI.
ng new magical-users
  1. Navigate into the project directory:
cd magical-users
  1. Start the development server:
ng serve

Open your browser and go to http://localhost:4200 to see the default Angular app running.

Step 2: Install Axios

  1. React: Installed Axios via npm.
  2. Angular: Angular recommends using the HttpClient module for HTTP requests. So, we'll set that up.

First, open src/app/app.module.ts and import HttpClientModule from @angular/common/http. Add HttpClientModule to the imports array.

Step 3: Clear the default project and Fetch Users

  1. React: Cleared src/App.js and fetched users using Axios.
  2. Angular:

Open src/app/app.component.ts:

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  users: any[] = [];

  constructor(private http: HttpClient) {}

  ngOnInit() {
    this.fetchUsers();
  }

  fetchUsers() {
    this.http.get('https://reqres.in/api/users')
      .subscribe(response => {
        this.users = response.data;
      }, error => {
        console.log('Error fetching users:', error);
      });
  }
}

Then, in src/app/app.component.html:

<h1>Magical Users</h1>
<div class="user-container">
  <app-user-card *ngFor="let user of users" [user]="user"></app-user-card>
</div>

Step 4: Create UserCard component

  1. React: Created UserCard.js.
  2. Angular: Generate a new component using Angular CLI:
ng generate component UserCard

In src/app/user-card/user-card.component.ts:

import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-user-card',
  templateUrl: './user-card.component.html',
  styleUrls: ['./user-card.component.css']
})
export class UserCardComponent {
  @Input() user: any;
  fullName = '';
  email = '';
  showMagic = false;

  ngOnChanges() {
    this.applyMagic();
  }

  applyMagic() {
    const nameParts = this.user.first_name.split('');
    const reversedName = nameParts.reverse().join('');
    const reversedEmail = this.user.email.split('').reverse().join('');
    this.fullName = `${reversedName} ${this.user.last_name}`;
    this.email = reversedEmail;
    this.showMagic = true;
  }

  toggleMagic() {
    this.showMagic = !this.showMagic;
  }
}

In src/app/user-card/user-card.component.html:

<div class="user-card">
  <h3>{{ fullName }}</h3>
  <p>{{ email }}</p>
  <p *ngIf="showMagic">🪄 Magic Applied!</p>
  <button (click)="toggleMagic()">{{ showMagic ? 'Remove Magic' : 'Apply Magic' }}</button>
</div>

Step 5: Add some styles

The styling remains largely the same. Add the provided styles to src/styles.css.

Step 6: Run the app

With ng serve running, visit http://localhost:4200. You should see the app functioning similarly to the React version.


Angular Concepts & Contrasts with React:

  1. Angular CLI vs. Create React App:

    • Angular CLI is a robust tool to scaffold, develop, and maintain Angular apps. React uses Create React App for bootstrapping projects.
  2. Angular Components vs. React Components:

    • Both frameworks use components as core building blocks.
    • React uses function or class components, while Angular uses a class with associated metadata.
  3. HttpClient vs. Axios:

    • In React, Axios is a popular choice for HTTP requests. In Angular, the framework provides the HttpClient module.
  4. State & Lifecycle:

    • React has useState and lifecycle methods/hooks like useEffect.
    • Angular components have lifecycle hooks like ngOnInit (similar to componentDidMount) and properties for state.
  5. Input & Props:

    • In React, data is passed to child components via props.
    • Angular uses the @Input() decorator to receive data from parent components.
  6. Event Handling:

    • React uses camelCase event names (onClick).
    • Angular uses event binding syntax ((click)).
  7. Conditional Rendering:

    • React uses conditional rendering with JavaScript logic (&& or ternary operators).
    • Angular uses structural directives like *ngIf.
  8. Styling:

    • Both React and Angular support component-scoped styles, but the mechanisms differ.

By the end of this exercise, React freshers should grasp Angular's architecture, data flow, component structure, and HTTP mechanisms. Contrasting Angular and React provides a solid understanding, facilitating the transition between frameworks.

Originally posted by @akash-coded in #159

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions