FSD Unit 4
FSD Unit 4
<button (click)="logout()">Logout</button>
4. Attribute/Style/Class Binding
<div [class.active]="isActive"></div>
<div [style.color]="isWarning ? 'red' : 'black'"></div>
Features of Angular Expressions
Feature Description
No this keyword You refer to component properties directly (name, not this.name)
No control flow Cannot use if, for, while, etc.
Type-safe Only access component members (properties/methods)
Safe navigation Use ?. to avoid errors with null/undefined: user?.name
Not Allowed in Angular Expressions
Assignments: a = 10
Declarations: let, var, const
Loops or conditionals: if, for
Accessing global variables like window, document, console (for security reasons)
AngularJS Expressions (for comparison)
In AngularJS (1.x), expressions looked similar:
<p>{{ 1 + 2 }}</p>
<p>{{ user.name }}</p>
But they were evaluated differently (in the scope context, not component class), and you could use
filters like:
{{ price | currency:"USD$" }}
Summary
Use Case Expression Format Example
Interpolation {{ expression }} {{ username }}
Property Binding [property]="expression" [src]="imageUrl"
Event Binding (event)="expression" (click)="save()"
Style/Class [class.xyz]="isTrue" [style.color]="color"
************************************************************************
Data Binding in Angular
Data binding in Angular is a powerful feature that connects the component (TypeScript logic) with
the view (HTML template). It allows data to flow between the UI and the component automatically.
Purpose of Data Binding
Display dynamic data in the view.
Respond to user interactions.
Synchronize data between component and template.
Types of Data Binding in Angular
Angular provides 4 main types of data binding:
1. Interpolation – One-Way (Component ➡️ View)
Displays data from the component in the template.
Syntax: {{ expression }}
Example:
tml
CopyEdit
<p>Hello, {{ username }}</p>
2. Property Binding – One-Way (Component ➡️ View)
Binds DOM properties to component values.
Syntax: [property]="expression"
Example:
<img [src]="user.profilePictureUrl">
<button [disabled]="isLoading">Submit</button>
3. Event Binding – One-Way (View ➡️ Component)
Sends user actions (clicks, typing, etc.) to the component.
Syntax: (event)="handlerFunction()"
Example:
<button (click)="logout()">Logout</button>
4. Two-Way Binding – (Component ⬌ View)
Syncs data both ways using [(ngModel)].
Requires importing FormsModule.
Syntax: [(ngModel)]="property"
Example:
<input [(ngModel)]="user.name">
*************************************************************************
Built in Directive vs Custom Directives
Types of Directives in Angular
Angular provides two categories:
1. Built-in Directives
These are provided by Angular itself.
2. Custom Directives
These are user-defined and extend or customize behavior.
1. Built-in Directives
There are three types of built-in directives:
A. Structural Directives
Change the structure/layout of the DOM (add/remove elements).
Directive Purpose
Conditionally include or remove an
*ngIf
element
*ngFor Repeat a block for each item in a list
*ngSwitch, *ngSwitchCase, *ngSwitchDefault Conditional multi-branch rendering
Example:
<div *ngIf="isLoggedIn">Welcome!</div>
<ul>
<li *ngFor="let item of items">{{ item }}</li>
</ul>
B. Attribute Directives
Change the appearance or behavior of an element.
Directive Purpose
ngClass Dynamically set CSS classes
ngStyle Dynamically set styles
ngModel Two-way data binding to form inputs (in FormsModule)
Example:
html
CopyEdit
<p [ngClass]="{active: isActive}">Status</p>
<p [ngStyle]="{'color': isError ? 'red' : 'green'}">Message</p>
<input [(ngModel)]="user.name">
C. Component Directives
Technically, every component is a directive with a template.
2. Custom Directives
You can build your own directives for reusable logic or custom DOM behavior.
Example: Custom Attribute Directive
Step 1: Create Directive
bash
CopyEdit
ng generate directive highlight
Step 2: Code – highlight.directive.ts
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[appHighlight]' // use like an attribute
})
export class HighlightDirective {
constructor(private el: ElementRef) {}
@HostListener('mouseenter') onMouseEnter() {
this.highlight('yellow');
}
@HostListener('mouseleave') onMouseLeave() {
this.highlight('');
}
private highlight(color: string) {
this.el.nativeElement.style.backgroundColor = color;
}
}
Step 3: Use in Template
<p appHighlight>Hover over this text to highlight it!</p>
Summary Table
Type Examples Purpose
Structural *ngIf, *ngFor, *ngSwitch Add/remove DOM elements
Attribute ngClass, ngStyle, ngModel Change look/behavior
Custom appHighlight, appAutoFocus Your own DOM behavior
*************************************************************************
MEAN STACK – ENVIRONMENT CREATION
The below 10 steps are common for both MERN and MEAN stack. Later steps differentiate
with react and angular
1. Create fullstack directory and go to that directory
2. Go to that directory and install node and npm
3. Create backend directory (all your server app files will be here) and run this command
npm init -y
4. In the same directory install express using this command npm install express
5. In the same directory install mongodb from official website and mongodb driver using npm
command.
6. Create server.js file in same directory and copy the below content to it. This is your actually http
server. You may have to add paths in it when ever you wanted to add server side applications and
access them through http request that is you need to define route.
const express = require('express');
const app = express();
const PORT = 3000;
// Define a basic route
app.get('/', (req, res) => {
res.send('Hello, world!');
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
7. Check whether you installed node correctly or not. Type the following command
node -v
8. check whether your nodes server is running correctly by starting it.
node server.js
9. check whether your mongodb is installed correctly. Start its service by using following command
in linux --> sudo systemctl start mongod
in windows -- >net start MongoDB or goto services and start manually
To connect to mongodb, run command mongosh ( mongosh )
10. check whether express is installed correctly
npm list express
If above 10 steps are correct then it means you have node, express and mongodb perfectly in your
machine.
Installing ANGULAR– Above 10 steps are common. Below are additional steps for react.
1. Create Frontend-angular-client folder, go to that folder and Install react.
npm install -g @angular/cli (cli-command line interface)
2. To check if installation happened successfully – run this command
ng version
3. To create angular app folder, run this command
ng new my-angular-app
3. To start angulars – Development server , run this command
ng serve
go to localhost:4200 to check your angular development server is up and running.
**********************************************************************
Important -- Creating routing in Angular
1. Generate an application
The following command uses the Angular CLI to generate a basic Angular application with
application routes. The application name in the following example is routing-app.
ng new routing-app
2. Adding components for routing
To use the Angular router, an application needs to have at least two components so that it can
navigate from one to the other. To create a component using the CLI, enter the following at the
command line where first is the name of your component:
ng generate component first
Repeat this step for a second component but give it a different name. Here, the new name is second.
ng generate component second
The CLI automatically appends Component, so if you were to write first-component, your
component would be FirstComponentComponent.
3. Importing your new components in routes.ts file in app folder
To use your new components, import them into app.routes.ts at the top of the file, as follows:
import {FirstComponent} from './first/first.component';
import {SecondComponent} from './second/second.component';
Also update routes in same file
content_copyconst routes: Routes = [
{ path: 'first-component', component: FirstComponent },
{ path: 'second-component', component: SecondComponent },
];
4. Add your routes to your application in appcomponent.html
Now that you have defined your routes, add them to your application. First, add links to the two
components. Assign the anchor tag that you want to add the route to the routerLink attribute.
Set the value of the attribute to the component to show when a user clicks on each link. Next,
update your component template to include <router-outlet>. This element informs Angular to
update the application view with the component for the selected route.
<h1>Angular Router App</h1>
<nav>
<ul>
<li><a routerLink="/first-component" routerLinkActive="active"
ariaCurrentWhenActive="page">First Component</a></li>
<li><a routerLink="/second-component" routerLinkActive="active"
ariaCurrentWhenActive="page">Second Component</a></li>
</ul>
</nav>
<!-- The routed views render in the <router-outlet>-->
<router-outlet></router-outlet>
Now, you can access first and second components using urls
**********************************************************************