-
Notifications
You must be signed in to change notification settings - Fork 4
Description
Let's recreate the "Emoji Fun" app in Angular, and during the process, I'll contrast Angular's features with React's, explaining the equivalent concepts in both frameworks.
Creating "Emoji Fun" App in Angular
Step 1: Setup
- React: You initialized the React app using Create React App.
- Angular: Initialize a new Angular app using Angular CLI.
ng new emoji-fun- Navigate into the project directory:
cd emoji-fun- Start the development server:
ng serveOpen your browser and go to http://localhost:4200 to see the default Angular app running.
Step 2: Clear the default project
- React: You cleared
src/App.js. - Angular: Open
src/app/app.component.htmland remove the existing code.
Replace it with:
<h1>Emoji Fun</h1>Step 3: Create EmojiSelector component
- React: You created a new file
EmojiSelector.js. - Angular: Generate a new component using Angular CLI:
ng generate component EmojiSelector- Open
src/app/emoji-selector/emoji-selector.component.tsand modify the code:
import { Component, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-emoji-selector',
templateUrl: './emoji-selector.component.html',
styleUrls: ['./emoji-selector.component.css']
})
export class EmojiSelectorComponent {
emojis = ['😄', '🥳', '🎉', '🎈', '🤩', '😎'];
@Output() emojiSelected = new EventEmitter<string>();
onSelect(emoji: string) {
this.emojiSelected.emit(emoji);
}
}- Then, open
src/app/emoji-selector/emoji-selector.component.html:
<h2>Select an Emoji</h2>
<div class="emoji-container">
<span *ngFor="let emoji of emojis"
class="emoji"
(click)="onSelect(emoji)">
{{emoji}}
</span>
</div>Step 4: Import and use EmojiSelector in App component
- React: You managed state using the
useStatehook. - Angular: You'll use the component's class properties and methods.
Open src/app/app.component.ts and modify:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
selectedEmoji: string | null = null;
handleEmojiSelect(emoji: string) {
this.selectedEmoji = emoji;
}
}Then, modify src/app/app.component.html:
<h1>Emoji Fun</h1>
<div *ngIf="selectedEmoji">
<h2>You selected:</h2>
<span class="emoji">{{selectedEmoji}}</span>
</div>
<app-emoji-selector (emojiSelected)="handleEmojiSelect($event)"></app-emoji-selector>Step 5: Add some styles
The styling remains 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.
Contrasts & Explanations:
-
Initialization:
- React: Uses
create-react-app. - Angular: Uses Angular CLI's
ng new.
- React: Uses
-
Component Creation:
- React: Manually create a new file.
- Angular: Use Angular CLI's
ng generate component.
-
State Management:
- React: Uses hooks like
useState. - Angular: Uses component's properties for state. No special hooks are required.
- React: Uses hooks like
-
Props vs. Input/Output:
- React: Uses props to pass data down and callbacks to communicate upwards.
- Angular: Uses
@Input()and@Output()decorators. For upward communication, Angular usesEventEmitter.
-
Rendering & Directives:
- React: Uses JSX and built-in directives like
map. - Angular: Uses HTML templates with Angular-specific directives, like
*ngForand*ngIf.
- React: Uses JSX and built-in directives like
-
Styling:
- Both frameworks support scoped styles for components. The styling method is largely the same.
-
Event Handling:
- React: Uses camelCase event names like
onClick. - Angular: Uses event binding syntax,
(click).
- React: Uses camelCase event names like
By the end of this exercise, React freshers should have a good understanding of Angular's component architecture, how data flows between components, and how Angular templates work. They'll also have insight into the parallels and differences between React and Angular, helping them transition seamlessly between the two frameworks.
Angular Concepts Explained
Let's dive deep into each Angular concept involved in the "Emoji Fun" exercise:
1. Angular CLI (Command Line Interface)
In-Depth Explanation: The Angular CLI is a command-line tool that helps you initialize, develop, scaffold, and maintain Angular applications. It provides commands for creating new components, services, and other building blocks.
Syntax Variations:
- To create a new Angular project:
ng new project-name - To create a new component:
ng generate component component-nameorng g c component-name - To start the development server:
ng serve
Real-World Use-Cases: Using Angular CLI to scaffold new projects, generate services, components, directives, and build and deploy applications.
2. Angular Components
In-Depth Explanation: Components are the fundamental building blocks of Angular applications. They encapsulate the data, the HTML template, and the logic for a view. Each component is associated with an HTML template and a TypeScript class.
Syntax Variations:
- Decorator
@Componentmarks a class as an Angular component and provides metadata.
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponent { }Real-World Use-Cases: Creating reusable UI widgets, encapsulating view logic, breaking down large applications into smaller, manageable pieces.
3. Templates, Directives, and Data Binding
In-Depth Explanation: Angular uses templates to render the component's view. Templates can use directives to control the structure of the DOM and data binding to display data and handle user interactions.
- Directives: Modify the structure and appearance of the DOM. Examples include
*ngIffor conditional rendering and*ngForfor rendering lists. - Data Binding: Syncs data between the component's class and the template. Examples include:
- Interpolation:
{{data}} - Property Binding:
[property]="data" - Event Binding:
(event)="handler()"
- Interpolation:
Real-World Use-Cases: Rendering dynamic data, creating lists, handling user inputs, toggling visibility of elements.
4. @input() and @output() Decorators
In-Depth Explanation:
- @input(): Allows parent components to pass data down to child components.
- @output(): Allows child components to emit custom events to parent components, often used with
EventEmitter.
Syntax Variations:
@Input() itemName: string;
@Output() itemSelected = new EventEmitter<string>();Real-World Use-Cases: Creating reusable components that accept inputs and notify parents of changes or actions, e.g., custom form controls, alert boxes, data tables.
5. Event Handling
In-Depth Explanation: Angular provides a way to bind component logic to events raised from DOM elements, like button clicks or input changes.
Syntax: (event)="handlerMethod()"
Example: (click)="onSelect(emoji)"
Real-World Use-Cases: Handling button clicks, form submissions, input changes, and more.
6. State Management in Components
In-Depth Explanation: Angular components maintain their state in class properties. State can be changed based on user interactions, data fetches, etc., and is automatically reflected in the view due to Angular's change detection mechanism.
Real-World Use-Cases: Storing user input, tracking UI state (e.g., a dropdown being open or closed), storing data fetched from an API.
7. Styles and Scoped CSS
In-Depth Explanation: Angular components have associated styles that are scoped to them, meaning the styles won't unintentionally affect other parts of the application.
Real-World Use-Cases: Styling specific components without affecting others, theming components, adding animations.
By understanding these fundamental concepts, learners can effectively create Angular applications with a solid grasp of the underlying principles. Comparing and contrasting these concepts with React will further solidify their understanding and allow them to transition between the frameworks seamlessly.
Originally posted by @akash-coded in #158