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
- React: Initialized the React app using Create React App.
- Angular: Initialize a new Angular app using Angular CLI.
- Navigate into the project directory:
- Start the development server:
Open your browser and go to http://localhost:4200 to see the default Angular app running.
Step 2: Install Axios
- React: Installed Axios via npm.
- 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
- React: Cleared
src/App.js and fetched users using Axios.
- 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
- React: Created
UserCard.js.
- 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:
-
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.
-
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.
-
HttpClient vs. Axios:
- In React, Axios is a popular choice for HTTP requests. In Angular, the framework provides the
HttpClient module.
-
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.
-
Input & Props:
- In React, data is passed to child components via props.
- Angular uses the
@Input() decorator to receive data from parent components.
-
Event Handling:
- React uses camelCase event names (
onClick).
- Angular uses event binding syntax (
(click)).
-
Conditional Rendering:
- React uses conditional rendering with JavaScript logic (
&& or ternary operators).
- Angular uses structural directives like
*ngIf.
-
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
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
cd magical-usersOpen your browser and go to
http://localhost:4200to see the default Angular app running.Step 2: Install Axios
HttpClientmodule for HTTP requests. So, we'll set that up.First, open
src/app/app.module.tsand importHttpClientModulefrom@angular/common/http. AddHttpClientModuleto theimportsarray.Step 3: Clear the default project and Fetch Users
src/App.jsand fetched users using Axios.Open
src/app/app.component.ts:Then, in
src/app/app.component.html:Step 4: Create UserCard component
UserCard.js.In
src/app/user-card/user-card.component.ts:In
src/app/user-card/user-card.component.html: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 serverunning, visithttp://localhost:4200. You should see the app functioning similarly to the React version.Angular Concepts & Contrasts with React:
Angular CLI vs. Create React App:
Angular Components vs. React Components:
HttpClient vs. Axios:
HttpClientmodule.State & Lifecycle:
useStateand lifecycle methods/hooks likeuseEffect.ngOnInit(similar tocomponentDidMount) and properties for state.Input & Props:
@Input()decorator to receive data from parent components.Event Handling:
onClick).(click)).Conditional Rendering:
&&or ternary operators).*ngIf.Styling:
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