Angular
Angular
Introduction to Angular
Prerequisites:
3. Project Setup
ng new my-app
platformBrowserDynamic().bootstrapModule(AppModule);
5. Building Components
● Generate a component:
bash
CopyEdit
○ Or shorthand: ng g c component-name
● A component includes:
○ .html: template
○ .css/.scss: styles
Example:
@Component({
selector: 'app-hello',
templateUrl: './hello.component.html',
styleUrls: ['./hello.component.css']
})
export class HelloComponent {
message = 'Hello, Angular!';
}
src/
├── app/
│ ├── app.component.ts/html/css
│ ├── app.module.ts
│ └── [other components, services, modules]
├── assets/
├── environments/
├── index.html
├── main.ts
└── styles.css
✅ Nesting Components:
Use the child component selector in the parent’s template:
2. Setting Up Templates
You can define templates in:
templateUrl: './child.component.html'
2. In component template:
<input [(ngModel)]="username" />
<p>Hello, {{ username }}!</p>
<app-child [childMessage]="messageFromParent"></app-child>
Child:(ts)
@Input() childMessage: string;
html:
<p>Child says: {{ childMessage }}</p>
Child:ts
sendMessage() {
this.messageEvent.emit('Hello from Child!');
}
Html:
<button (click)="sendMessage()">Send to Parent</button>
Parent:html
<app-child (messageEvent)="receiveMessage($event)"></app-child>
<p>Received: {{ message }}</p>
Ts:
receiveMessage(msg: string) {
this.message = msg;
}
✅ Summary
Feature Purpose
✅ Structural Directives
Change the structure of the DOM.
✅ Attribute Directives
Change the appearance or behavior of an element.
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
@HostListener('mouseenter') onMouseEnter() {
this.renderer.setStyle(this.el.nativeElement, 'backgroundColor',
'yellow');
}
@HostListener('mouseleave') onMouseLeave() {
this.renderer.removeStyle(this.el.nativeElement,
'backgroundColor');
}
}
🔹 3. Applying Styles
✅ Inline styles
<p style="color: blue;">Styled with inline CSS</p>
✅ Dynamic styles
<p [ngStyle]="{ 'color': dynamicColor }">Styled dynamically</p>
🔹 4. View Encapsulation
Angular applies style scoping using View Encapsulation. You can
control it via the encapsulation property.
ts:
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css'],
encapsulation: ViewEncapsulation.None // or Emulated / ShadowDom
})
Mode Description
🔹 5. Bootstrap Integration
✅ Install Bootstrap
npm install bootstrap
✅ Add to angular.json
"styles": [
"node_modules/bootstrap/dist/css/bootstrap.min.css",
"src/styles.css"
],
"scripts": [
"node_modules/bootstrap/dist/js/bootstrap.bundle.min.js"
]
✅ Summary
Feature Purpose
Example:
// app.module.ts
import { FormsModule } from '@angular/forms';
@NgModule({ imports: [FormsModule] })
● Requires ReactiveFormsModule.
Example:
// app.module.ts
import { ReactiveFormsModule } from '@angular/forms';
@NgModule({ imports: [ReactiveFormsModule] })
● Validators.minLength
● Validators.email
✅ Create a Service:
ng generate service data
ngOnInit() {
this.frameworks = this.dataService.getData();
}
🔹 5. Pipes
✅ Built-in Pipes:
● date, uppercase, lowercase, currency, percent, json, etc.
Example:
<p>{{ today | date:'shortDate' }}</p>
<p>{{ price | currency:'USD' }}</p>
✅ Custom Pipe:
generate with CLI:
capitalize.pipe.ts
@Pipe({ name: 'capitalize' })
export class CapitalizePipe implements PipeTransform {
transform(value: string): string {
return value.charAt(0).toUpperCase() + value.slice(1);
}
}
Usage in template:
✅ Summary Table
✅ Navigation
Use the routerLink directive:
Or navigate programmatically:
this.router.navigate(['/users', userId]);
✅ Child Routes
const routes: Routes = [
{
path: 'dashboard',
component: DashboardComponent,
children: [
{ path: 'stats', component: StatsComponent },
{ path: 'settings', component: SettingsComponent }
]
}
];
✅ Route Parameters
In the component:
✅ Example Service
@Injectable({ providedIn: 'root' })
export class UserService {
constructor(private http: HttpClient) {}
getUsers(): Observable<User[]> {
return this.http.get<User[]>('/api/users');
}
✅ In Component
ngOnInit() {
this.userService.getUsers().subscribe(users => this.users = users);
}
✅ Auth Interceptor
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler) {
const token = localStorage.getItem('token');
if (token) {
const cloned = req.clone({
headers: req.headers.set('Authorization', `Bearer ${token}`)
});
return next.handle(cloned);
}
return next.handle(req);
}
}
Provide in module:
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true
}
]
canActivate(): boolean {
if (this.authService.isAuthenticated()) {
return true;
}
this.router.navigate(['/login']);
return false;
}
}
✅ Summary Table
Feature Purpose
@NgModule({
imports: [RouterModule.forRoot(routes, { preloadingStrategy:
PreloadAllModules })]
})
Use in routes:
{ path: 'admin', loadChildren: () =>
import('./admin/admin.module').then(m => m.AdminModule), data: {
preload: true } }
In app-routing.module.ts:
RouterModule.forRoot(routes, { preloadingStrategy:
CustomPreloadingStrategy })
✅ CanDeactivate Example
Create a component interface:
Guard:
@Injectable({ providedIn: 'root' })
export class ConfirmDeactivateGuard implements
CanDeactivate<CanComponentDeactivate> {
canDeactivate(component: CanComponentDeactivate) {
return component.canDeactivate ? component.canDeactivate() : true;
}
}
Component:
canDeactivate(): boolean {
return confirm('Unsaved changes. Leave page?');
}
Route:
{ path: 'edit', component: EditComponent, canDeactivate:
[ConfirmDeactivateGuard] }
Guard:
Route:
{ path: 'user/:id', component: UserComponent, resolve: { user:
UserResolver } }
Component:
ngOnInit() {
this.route.data.subscribe(data => this.user = data['user']);
}
✅ Summary
Feature Description