Intermediate Angular Questions - Part 1FrontendAngularIntermediate
Angular Framework — Intermediate Concepts & Advanced Patterns (Part 1).
Guía de preguntas y respuestas de nivel intermedio sobre Angular: formularios reactivos dinámicos (FormArray), operadores y patrones avanzados con RxJS, inyección de dependencias jerárquica (providedIn, @Optional, @Self, @SkipSelf), componentes dinámicos (ViewContainerRef, createComponent), directivas personalizadas, pipes puros e impuros, estrategias de detección de cambios (OnPush), ciclo de vida, enrutamiento con guards y resolvers, y comunicación entre componentes.
1. How do you create a dynamic form in Angular using `FormArray`?
`FormArray` is used to manage a collection of form controls in Angular reactive forms.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormArray } from '@angular/forms';
@Component({
selector: 'app-dynamic-form',
template: `
`,
})
export class DynamicFormComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
items: this.fb.array([])
});
}
get items() {
return this.form.get('items') as FormArray;
}
addItem() {
this.items.push(this.fb.control(''));
}
}
2. How do you implement lazy loading in Angular?
Lazy loading is implemented using Angular's routing module by defining routes with a loadChildren property.
const routes: Routes = [
{
path: 'feature',
loadChildren: () => import('./feature/feature.module').then(m => m.FeatureModule)
}
];
3. How can you handle HTTP errors in Angular?
HTTP errors can be handled using Angular's `HttpInterceptor` to catch and process HTTP errors globally.
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpErrorResponse } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler) {
return next.handle(req).pipe(
catchError((error: HttpErrorResponse) => {
// Handle error
console.error('HTTP Error:', error);
return throwError(error);
})
);
}
}
4. How do you use Angular's `ContentChildren` to query for content?
`@ContentChildren` allows querying of projected content in Angular.
import { Component, ContentChildren, QueryList, AfterContentInit } from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
selector: 'app-parent',
template: `
`,
})
export class ParentComponent implements AfterContentInit {
@ContentChildren(ChildComponent) children: QueryList;
ngAfterContentInit() {
console.log(this.children.toArray());
}
}
5. How do you use Angular's `ngIf` with `else` syntax?
The `ngIf` directive can be used with `else` to conditionally display alternate content.
@Component({
selector: 'app-example',
template: `
Content is visible
Content is not visible
`,
})
export class ExampleComponent {
isVisible = true;
}
6. How do you use Angular's `ngFor` with `trackBy` function?
The `trackBy` function is used to optimize the rendering of lists by tracking changes to items in the list.
@Component({
selector: 'app-example',
template: `
{{ item.name }}
`,
})
export class ExampleComponent {
items = [{ id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2' }];
trackById(index: number, item: any) {
return item.id;
}
}
7. How do you create a custom Angular pipe?
A custom pipe is created to transform data in the template.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'reverse'
})
export class ReversePipe implements PipeTransform {
transform(value: string): string {
return value.split('').reverse().join('');
}
}
8. How do you use Angular's `@HostListener` decorator?
`@HostListener` allows listening to events on the host element of a directive or component.
import { Directive, HostListener } from '@angular/core';
@Directive({
selector: '[appHover]'
})
export class HoverDirective {
@HostListener('mouseenter') onMouseEnter() {
console.log('Mouse entered');
}
@HostListener('mouseleave') onMouseLeave() {
console.log('Mouse left');
}
}
9. How do you handle form validation in Angular?
Form validation can be handled using Angular's reactive forms and built-in validators.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-form',
template: `
`,
})
export class FormComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
name: ['', Validators.required]
});
}
onSubmit() {
console.log(this.form.value);
}
}
10. How do you use Angular's `@Inject` decorator?
The `@Inject` decorator is used to specify the provider to be injected into a class.
import { Injectable, Inject } from '@angular/core';
import { API_URL } from './tokens';
@Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(@Inject(API_URL) private apiUrl: string) { }
}
11. How do you implement custom error handling in Angular services?
Custom error handling can be implemented using Angular's `HttpInterceptor` to catch and handle HTTP errors.
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpErrorResponse } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';
@Injectable()
export class CustomErrorInterceptor implements HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler) {
return next.handle(req).pipe(
catchError((error: HttpErrorResponse) => {
// Custom error handling logic
console.error('An error occurred:', error.message);
return throwError(error);
})
);
}
}
12. How do you create a reusable Angular component?
A reusable component is created by defining it with a selector and providing inputs and outputs.
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-reusable',
template: `
`,
})
export class ReusableComponent {
@Input() label: string;
@Output() clicked = new EventEmitter();
onClick() {
this.clicked.emit();
}
}
13. How do you use Angular's Dependency Injection system?
Dependency Injection is used to inject services or other dependencies into components or services.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class DataService {
getData() {
return ['Item 1', 'Item 2'];
}
}
14. How do you manage application state in Angular?
Application state can be managed using services, or state management libraries like NgRx or Akita.
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class StateService {
private state = new BehaviorSubject({});
state$ = this.state.asObservable();
setState(newState: any) {
this.state.next(newState);
}
}
15. How do you configure Angular's build and deployment settings?
Build and deployment settings are configured in the `angular.json` file.
{
"projects": {
"my-app": {
"architect": {
"build": {
"options": {
"outputPath": "dist/my-app",
"index": "src/index.html",
"main": "src/main.ts",
"tsConfig": "tsconfig.app.json"
}
}
}
}
}
}
16. How do you implement Angular route guards?
Route guards are used to control access to routes based on conditions.
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private router: Router) { }
canActivate(): boolean {
// Check authentication status
const isAuthenticated = false;
if (!isAuthenticated) {
this.router.navigate(['/login']);
return false;
}
return true;
}
}
17. How do you use Angular's `HttpClient` for making HTTP requests?
`HttpClient` is used for making HTTP requests to a backend API.
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(private http: HttpClient) { }
getData() {
return this.http.get('https://api.example.com/data');
}
}
18. How do you create and use Angular services?
Services are used to share data and logic across multiple components.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class DataService {
getData() {
return ['Item 1', 'Item 2'];
}
}
19. How do you use Angular's `@Input` and `@Output` decorators?
`@Input` is used to pass data to a child component, and `@Output` is used to emit events from a child component.
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
template: ``,
})
export class ChildComponent {
@Input() data: string;
@Output() notifyEvent = new EventEmitter();
notify() {
this.notifyEvent.emit('Notification from child');
}
}
20. How do you use Angular's `@ViewChild` decorator?
`@ViewChild` is used to access a child component or DOM element from the parent component.
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
@Component({
selector: 'app-parent',
template: `Paragraph
`,
})
export class ParentComponent implements AfterViewInit {
@ViewChild('paragraph') paragraph: ElementRef;
ngAfterViewInit() {
console.log(this.paragraph.nativeElement.textContent);
}
}
Intermediate Angular Questions - Part 2
21. How do you use Angular's `ngSwitch` directive?
The `ngSwitch` directive is used to conditionally display one of several elements based on the value of an expression.
@Component({ selector: 'app-switch', template: `
Case A
Case B
Default case`, }) export class SwitchComponent { value = 'A'; }
22. How do you implement a custom Angular directive?
Custom directives can be created to modify the behavior or appearance of elements.
import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(private el: ElementRef, private renderer: Renderer2) { }
@HostListener('mouseenter') onMouseEnter() {
this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'yellow');
}
@HostListener('mouseleave') onMouseLeave() {
this.renderer.removeStyle(this.el.nativeElement, 'backgroundColor');
}
}
23. How do you configure Angular's HTTP interceptors?
HTTP interceptors are used to modify HTTP requests and responses.
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { ErrorInterceptor } from './error.interceptor';
@NgModule({
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true }
]
})
export class AppModule { }
24. How do you use Angular's `@HostBinding` decorator?
The `@HostBinding` decorator binds a property of the host element to a property of the directive or component.
import { Directive, HostBinding } from '@angular/core';
@Directive({
selector: '[appClass]'
})
export class ClassDirective {
@HostBinding('class.active') isActive = true;
}
25. How do you use Angular's `@ViewChildren` decorator?
The `@ViewChildren` decorator is used to query for multiple elements or directives in the template.
import { Component, ViewChildren, QueryList, AfterViewInit } from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
selector: 'app-parent',
template: `
`,
})
export class ParentComponent implements AfterViewInit {
@ViewChildren(ChildComponent) childComponents: QueryList;
ngAfterViewInit() {
console.log(this.childComponents.toArray());
}
}
26. How do you handle asynchronous operations in Angular components?
Asynchronous operations can be handled using RxJS observables and operators.
import { Component, OnInit } from '@angular/core'; import { ApiService } from './api.service'; @Component({ selector: 'app-data', template: `{{ data | json }}`, }) export class DataComponent implements OnInit { data$ = this.apiService.getData(); constructor(private apiService: ApiService) { } ngOnInit() { } }
27. How do you use Angular's `@ContentChild` decorator?
The `@ContentChild` decorator allows querying for a single projected content element.
import { Component, ContentChild, AfterContentInit } from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
selector: 'app-parent',
template: ` `,
})
export class ParentComponent implements AfterContentInit {
@ContentChild(ChildComponent) child: ChildComponent;
ngAfterContentInit() {
console.log(this.child);
}
}
28. How do you use Angular's `ngClass` directive?
The `ngClass` directive is used to add or remove CSS classes dynamically.
@Component({ selector: 'app-example', template: `Conditional classes`, }) export class ExampleComponent { isActive = true; toggle() { this.isActive = !this.isActive; } }
29. How do you use Angular's `ngModel` for two-way data binding?
The `ngModel` directive is used for two-way data binding between the form control and the component.
import { Component } from '@angular/core'; @Component({ selector: 'app-two-way-binding', template: `
{{ value }}`, }) export class TwoWayBindingComponent { value = 'Initial value'; }
30. How do you use Angular's `@Injectable` decorator for services?
The `@Injectable` decorator marks a class as a service that can be injected into other components or services.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ExampleService {
getData() {
return ['Data 1', 'Data 2'];
}
}
31. How do you use Angular's `Router` service for navigation?
The `Router` service is used to programmatically navigate between routes.
import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-navigate',
template: `
`,
})
export class NavigateComponent {
constructor(private router: Router) { }
goToHome() {
this.router.navigate(['/home']);
}
}
32. How do you implement Angular's route resolvers?
Route resolvers are used to fetch data before navigating to a route.
import { Injectable } from '@angular/core';
import { Resolve, RouterStateSnapshot, ActivatedRouteSnapshot } from '@angular/router';
import { Observable } from 'rxjs';
import { ApiService } from './api.service';
@Injectable({
providedIn: 'root'
})
export class DataResolver implements Resolve {
constructor(private apiService: ApiService) { }
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable {
return this.apiService.getData();
}
}
33. How do you create Angular form controls dynamically?
Dynamic form controls can be created using Angular's `FormBuilder` service.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'app-dynamic-form',
template: `
`,
})
export class DynamicFormComponent {
formGroup: FormGroup;
constructor(private fb: FormBuilder) {
this.formGroup = this.fb.group({
dynamicControl: ['']
});
}
}
34. How do you implement Angular's `ngFor` directive with trackBy?
The `trackBy` function improves performance by tracking items by their identity.
@Component({
selector: 'app-list',
template: `
{{ item.name }}
`,
})
export class ListComponent {
items = [{ id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2' }];
trackByFn(index: number, item: any) {
return item.id;
}
}
35. How do you implement Angular's `ngIf` directive with `else`?
The `ngIf` directive can conditionally display elements with an `else` block.
@Component({ selector: 'app-condition', template: `VisibleNot visible `, }) export class ConditionComponent { isVisible = true; }
36. How do you use Angular's `HttpClient` for POST requests?
`HttpClient` is used for making POST requests to a backend API.
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(private http: HttpClient) { }
postData(data: any) {
return this.http.post('https://api.example.com/data', data);
}
}
37. How do you implement Angular's `FormArray` for dynamic forms?
The `FormArray` is used to manage an array of form controls.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormArray } from '@angular/forms';
@Component({
selector: 'app-dynamic-form-array',
template: `
`,
})
export class DynamicFormArrayComponent {
formGroup: FormGroup;
constructor(private fb: FormBuilder) {
this.formGroup = this.fb.group({
items: this.fb.array([this.fb.control('')])
});
}
get items() {
return this.formGroup.get('items') as FormArray;
}
addItem() {
this.items.push(this.fb.control(''));
}
}
38. How do you implement Angular's `ngOnDestroy` lifecycle hook?
The `ngOnDestroy` lifecycle hook is used to clean up resources when a component is destroyed.
import { Component, OnDestroy } from '@angular/core'; import { Subscription } from 'rxjs'; @Component({ selector: 'app-cleanup', template: `
Cleanup example`, }) export class CleanupComponent implements OnDestroy { private subscription: Subscription; ngOnDestroy() { this.subscription.unsubscribe(); } }
39. How do you use Angular's `ng-template` for template rendering?
The `ng-template` directive defines a template that can be reused or rendered conditionally.
@Component({ selector: 'app-template', template: `
{{ data }}`, }) export class TemplateComponent { }
40. How do you implement Angular's `ngFor` directive with `trackBy`?
The `trackBy` function helps Angular track items in a list and improve rendering performance.
@Component({
selector: 'app-track-by',
template: `
{{ item.name }}
`,
})
export class TrackByComponent {
items = [{ id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2' }];
trackByFn(index: number, item: any) {
return item.id;
}
}
Intermediate Angular Questions - Part 3
41. How do you use Angular's `@ViewChild` decorator with a static flag?
The `@ViewChild` decorator can be used with a static flag to determine when the query should be resolved.
import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
selector: 'app-parent',
template: ` `,
})
export class ParentComponent implements AfterViewInit {
@ViewChild(ChildComponent, { static: true }) child: ChildComponent;
ngAfterViewInit() {
console.log(this.child);
}
}
42. How do you implement Angular's `ngFor` directive with a `let` syntax?
The `let` syntax in `ngFor` allows you to define a variable for each item in the loop.
@Component({
selector: 'app-list',
template: `
-
{{ i + 1 }}: {{ item }}
`,
})
export class ListComponent {
items = ['Item 1', 'Item 2', 'Item 3'];
}
43. How do you use Angular's `@Input` and `@Output` decorators in parent-child communication?
The `@Input` decorator is used to pass data from a parent component to a child component, while the `@Output` decorator is used to emit events from the child to the parent.
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
template: `
`,
})
export class ChildComponent {
@Input() data: string;
@Output() notify = new EventEmitter();
notifyParent() {
this.notify.emit('Data from child');
}
}
@Component({
selector: 'app-parent',
template: `
`,
})
export class ParentComponent {
parentData = 'Data from parent';
handleNotification(message: string) {
console.log(message);
}
}
44. How do you use Angular's `@ContentChildren` decorator?
The `@ContentChildren` decorator queries for multiple projected content elements in a component.
import { Component, ContentChildren, QueryList, AfterContentInit } from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
selector: 'app-parent',
template: ` `,
})
export class ParentComponent implements AfterContentInit {
@ContentChildren(ChildComponent) children: QueryList;
ngAfterContentInit() {
this.children.forEach(child => console.log(child));
}
}
45. How do you use Angular's `FormGroup` and `FormControl` in reactive forms?
`FormGroup` and `FormControl` are used to create and manage reactive forms.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-reactive-form',
template: `
`,
})
export class ReactiveFormComponent {
formGroup: FormGroup;
constructor(private fb: FormBuilder) {
this.formGroup = this.fb.group({
name: ['', Validators.required]
});
}
onSubmit() {
console.log(this.formGroup.value);
}
}
46. How do you use Angular's `FormBuilder` service?
The `FormBuilder` service simplifies form creation and validation in Angular forms.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'app-builder-form',
template: `
`,
})
export class BuilderFormComponent {
formGroup: FormGroup;
constructor(private fb: FormBuilder) {
this.formGroup = this.fb.group({
email: ['']
});
}
}
47. How do you use Angular's `Validators` class for form validation?
The `Validators` class provides built-in validation functions for forms.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-validate-form',
template: `
`,
})
export class ValidateFormComponent {
formGroup: FormGroup;
constructor(private fb: FormBuilder) {
this.formGroup = this.fb.group({
email: ['', [Validators.required, Validators.email]]
});
}
onSubmit() {
console.log(this.formGroup.value);
}
}
48. How do you use Angular's `Router` for lazy loading?
Lazy loading allows modules to be loaded on demand, improving application performance.
const routes: Routes = [
{
path: 'lazy',
loadChildren: () => import('./lazy/lazy.module').then(m => m.LazyModule)
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
49. How do you handle form submission with Angular's `ReactiveForms`?
Form submission in reactive forms can be handled by subscribing to the form's `valueChanges` or `statusChanges` observable.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'app-reactive-form',
template: `
`,
})
export class ReactiveFormComponent {
formGroup: FormGroup;
constructor(private fb: FormBuilder) {
this.formGroup = this.fb.group({
name: ['']
});
this.formGroup.valueChanges.subscribe(value => {
console.log('Form value changed:', value);
});
}
onSubmit() {
console.log(this.formGroup.value);
}
}
50. How do you use Angular's `HttpInterceptor` for global HTTP handling?
An `HttpInterceptor` can be used to modify HTTP requests or responses globally.
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler): Observable> {
const clonedReq = req.clone({
setHeaders: {
Authorization: `Bearer your-token`
}
});
return next.handle(clonedReq);
}
}
51. How do you use Angular's `Router` for route guards?
Route guards can be used to control access to routes based on certain conditions.
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private router: Router) {}
canActivate(): boolean {
const isLoggedIn = false; // Replace with actual login check
if (!isLoggedIn) {
this.router.navigate(['/login']);
return false;
}
return true;
}
}
52. How do you use Angular's `Directive` to create a custom directive?
Custom directives can be created to extend HTML elements with additional behavior.
import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(private el: ElementRef, private renderer: Renderer2) {}
@HostListener('mouseenter') onMouseEnter() {
this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'yellow');
}
@HostListener('mouseleave') onMouseLeave() {
this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'transparent');
}
}
53. How do you use Angular's `ChangeDetectorRef` to manually trigger change detection?
The `ChangeDetectorRef` service allows you to manually control change detection.
import { Component, ChangeDetectorRef } from '@angular/core';
@Component({
selector: 'app-manual-detection',
template: `{{ message }}
`,
})
export class ManualDetectionComponent {
message = 'Initial message';
constructor(private cdRef: ChangeDetectorRef) {}
updateMessage() {
this.message = 'Updated message';
this.cdRef.detectChanges();
}
}
54. How do you use Angular's `EventEmitter` to communicate between components?
The `EventEmitter` class is used to emit custom events from child components to parent components.
import { Component, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
template: ``,
})
export class ChildComponent {
@Output() event = new EventEmitter();
sendEvent() {
this.event.emit('Data from child');
}
}
@Component({
selector: 'app-parent',
template: `
`,
})
export class ParentComponent {
handleEvent(message: string) {
console.log(message);
}
}
55. How do you use Angular's `NgModule` to create feature modules?
Feature modules allow you to organize application functionality into cohesive blocks.
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FeatureComponent } from './feature.component';
@NgModule({
declarations: [FeatureComponent],
imports: [CommonModule],
exports: [FeatureComponent]
})
export class FeatureModule { }
56. How do you use Angular's `NgZone` for managing change detection?
The `NgZone` service helps control Angular's change detection process manually.
import { Component, NgZone } from '@angular/core';
@Component({
selector: 'app-zone',
template: `{{ message }}
`,
})
export class ZoneComponent {
message = 'Initial message';
constructor(private ngZone: NgZone) {
this.ngZone.runOutsideAngular(() => {
setTimeout(() => {
this.message = 'Updated message';
this.ngZone.run(() => console.log('Change detected'));
}, 1000);
});
}
}
57. How do you use Angular's `@HostListener` to handle DOM events?
The `@HostListener` decorator allows you to listen to DOM events directly on the host element of a directive or component.
import { Directive, HostListener } from '@angular/core';
@Directive({
selector: '[appClickTracker]'
})
export class ClickTrackerDirective {
@HostListener('click', ['$event']) onClick(event: Event) {
console.log('Element clicked:', event);
}
}
58. How do you use Angular's `@ViewChildren` decorator for querying multiple elements?
The `@ViewChildren` decorator queries for multiple elements within the view of a component.
import { Component, ViewChildren, QueryList, AfterViewInit } from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
selector: 'app-parent',
template: ` `,
})
export class ParentComponent implements AfterViewInit {
@ViewChildren(ChildComponent) children: QueryList;
ngAfterViewInit() {
this.children.forEach(child => console.log(child));
}
}
59. How do you use Angular's `ngOnChanges` lifecycle hook?
The `ngOnChanges` lifecycle hook is used to respond to changes in input properties.
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
@Component({
selector: 'app-changes',
template: `{{ inputValue }}
`,
})
export class ChangesComponent implements OnChanges {
@Input() inputValue: string;
ngOnChanges(changes: SimpleChanges) {
console.log('Changes:', changes);
}
}
60. How do you use Angular's `ngOnInit` lifecycle hook?
The `ngOnInit` lifecycle hook is used for component initialization logic.
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-init',
template: `Component initialized
`,
})
export class InitComponent implements OnInit {
ngOnInit() {
console.log('Component initialized');
}
}
Intermediate Angular Questions - Part 4
61. How do you use Angular's `ngOnDestroy` lifecycle hook?
The `ngOnDestroy` lifecycle hook is used to clean up resources and unsubscribe from observables.
import { Component, OnDestroy } from '@angular/core'; import { Subscription } from 'rxjs'; @Component({ selector: 'app-destroy', template: `
Component destroyed`, }) export class DestroyComponent implements OnDestroy { private subscription: Subscription; ngOnDestroy() { // Unsubscribe to avoid memory leaks if (this.subscription) { this.subscription.unsubscribe(); } } }
62. How do you use Angular's `ngModel` for two-way data binding?
The `ngModel` directive is used for two-way data binding between form controls and component properties.
import { Component } from '@angular/core'; @Component({ selector: 'app-two-way-binding', template: `
Value: {{ value }}`, }) export class TwoWayBindingComponent { value: string = ''; }
63. How do you use Angular's `@HostBinding` decorator?
The `@HostBinding` decorator is used to bind a property of the host element to a property of the directive or component.
import { Directive, HostBinding } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
@HostBinding('class.highlight') isHighlighted = true;
}
64. How do you use Angular's `@HostListener` decorator to listen to DOM events?
The `@HostListener` decorator allows you to listen to events on the host element of the directive or component.
import { Directive, HostListener } from '@angular/core';
@Directive({
selector: '[appClickTracker]'
})
export class ClickTrackerDirective {
@HostListener('click', ['$event']) onClick(event: Event) {
console.log('Element clicked:', event);
}
}
65. How do you use Angular's `ngOnChanges` lifecycle hook?
The `ngOnChanges` lifecycle hook responds to changes in input properties.
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core'; @Component({ selector: 'app-changes', template: `
{{ inputValue }}`, }) export class ChangesComponent implements OnChanges { @Input() inputValue: string; ngOnChanges(changes: SimpleChanges) { console.log('Changes:', changes); } }
66. How do you use Angular's `ngOnInit` lifecycle hook?
The `ngOnInit` lifecycle hook is used for component initialization logic.
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-init', template: `
Component initialized`, }) export class InitComponent implements OnInit { ngOnInit() { console.log('Component initialized'); } }
67. How do you use Angular's `ngAfterViewInit` lifecycle hook?
The `ngAfterViewInit` lifecycle hook is used after the component's view and child views have been initialized.
import { Component, AfterViewInit, ViewChild, ElementRef } from '@angular/core'; @Component({ selector: 'app-view-init', template: `Content`, }) export class ViewInitComponent implements AfterViewInit { @ViewChild('myDiv') div: ElementRef; ngAfterViewInit() { console.log(this.div.nativeElement.textContent); } }
68. How do you use Angular's `ngAfterContentInit` lifecycle hook?
The `ngAfterContentInit` lifecycle hook is used after Angular initializes the content of the component.
import { Component, AfterContentInit, ContentChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-content-init',
template: ` `,
})
export class ContentInitComponent implements AfterContentInit {
@ContentChild('content') content: ElementRef;
ngAfterContentInit() {
console.log(this.content.nativeElement.textContent);
}
}
69. How do you use Angular's `ngAfterViewChecked` lifecycle hook?
The `ngAfterViewChecked` lifecycle hook is used after Angular checks the component's view and child views.
import { Component, AfterViewChecked } from '@angular/core'; @Component({ selector: 'app-view-checked', template: `
Check view`, }) export class ViewCheckedComponent implements AfterViewChecked { ngAfterViewChecked() { console.log('View checked'); } }
70. How do you use Angular's `ngAfterContentChecked` lifecycle hook?
The `ngAfterContentChecked` lifecycle hook is used after Angular checks the content projected into the component.
import { Component, AfterContentChecked } from '@angular/core'; @Component({ selector: 'app-content-checked', template: `
Check content`, }) export class ContentCheckedComponent implements AfterContentChecked { ngAfterContentChecked() { console.log('Content checked'); } }
71. How do you use Angular's `ngOnDestroy` lifecycle hook for cleanup?
The `ngOnDestroy` lifecycle hook is used to perform cleanup just before Angular destroys the component.
import { Component, OnDestroy } from '@angular/core'; import { Subscription } from 'rxjs'; @Component({ selector: 'app-destroy', template: `
Component destroyed`, }) export class DestroyComponent implements OnDestroy { private subscription: Subscription; ngOnDestroy() { // Unsubscribe to avoid memory leaks if (this.subscription) { this.subscription.unsubscribe(); } } }
72. How do you use Angular's `@Input` decorator for input binding?
The `@Input` decorator allows data to be passed from a parent component to a child component.
import { Component, Input } from '@angular/core'; @Component({ selector: 'app-child', template: `
{{ data }}`, }) export class ChildComponent { @Input() data: string; } @Component({ selector: 'app-parent', template: ``, }) export class ParentComponent { parentData = 'Data from parent'; }
73. How do you use Angular's `@Output` decorator for output binding?
The `@Output` decorator is used to emit events from a child component to a parent component.
import { Component, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'app-child', template: ``, }) export class ChildComponent { @Output() dataEvent = new EventEmitter(); sendData() { this.dataEvent.emit('Data from child'); } } @Component({ selector: 'app-parent', template: `
{{ receivedData }}`, }) export class ParentComponent { receivedData: string; receiveData(data: string) { this.receivedData = data; } }
74. How do you use Angular's `@ViewChild` decorator for querying a single element?
The `@ViewChild` decorator allows querying a single element or directive from the component's view.
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core'; @Component({ selector: 'app-view-child', template: `Content`, }) export class ViewChildComponent implements AfterViewInit { @ViewChild('myDiv') div: ElementRef; ngAfterViewInit() { console.log(this.div.nativeElement.textContent); } }
75. How do you use Angular's `NgModule` to create a shared module?
A shared module allows you to share common functionality across multiple modules.
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SharedComponent } from './shared.component';
@NgModule({
declarations: [SharedComponent],
imports: [CommonModule],
exports: [SharedComponent]
})
export class SharedModule { }
76. How do you use Angular's `@NgModule` to configure routes?
Routing configuration is done in the `@NgModule` decorator with the `RouterModule.forRoot` method.
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home.component';
import { AboutComponent } from './about.component';
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'about', component: AboutComponent },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
77. How do you use Angular's `ActivatedRoute` to access route parameters?
The `ActivatedRoute` service provides access to the route parameters of the active route.
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-route', template: `
Parameter: {{ param }}`, }) export class RouteComponent implements OnInit { param: string; constructor(private route: ActivatedRoute) {} ngOnInit() { this.route.paramMap.subscribe(params => { this.param = params.get('id'); }); } }
78. How do you use Angular's `RouterLink` directive for navigation?
79. How do you use Angular's `Router` service for programmatic navigation?
The `Router` service allows you to navigate programmatically to different routes.
import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-navigation',
template: ``,
})
export class NavigationComponent {
constructor(private router: Router) {}
navigate() {
this.router.navigate(['/about']);
}
}
80. How do you use Angular's `FormControl` to manage form inputs?
The `FormControl` class is used to manage the value and validation status of form inputs.
import { Component } from '@angular/core'; import { FormControl } from '@angular/forms'; @Component({ selector: 'app-form', template: `
Value: {{ nameControl.value }}`, }) export class FormComponent { nameControl = new FormControl(''); }
Intermediate Angular Questions - Part 5
81. How do you use Angular's `FormArray` to manage an array of form controls?
The `FormArray` class is used to manage an array of form controls.
import { Component } from '@angular/core';
import { FormArray, FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'app-form-array',
template: `
`,
})
export class FormArrayComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
items: this.fb.array([this.fb.control('')])
});
}
get items() {
return this.form.get('items') as FormArray;
}
addItem() {
this.items.push(this.fb.control(''));
}
}
82. How do you use Angular's `ReactiveForms` to create a form with validation?
Reactive forms allow you to create forms with validation using `FormControl` and `FormGroup` classes.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-reactive-form',
template: `
`,
})
export class ReactiveFormComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
name: ['', Validators.required]
});
}
onSubmit() {
console.log(this.form.value);
}
}
83. How do you use Angular's `FormBuilder` to create a form with nested controls?
The `FormBuilder` class helps create complex forms with nested controls.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'app-nested-form',
template: `
`,
})
export class NestedFormComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
address: this.fb.group({
street: [''],
city: ['']
})
});
}
}
84. How do you use Angular's `Validators` to add custom validation?
You can create custom validators and use them with form controls.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-custom-validation',
template: `
`,
})
export class CustomValidationComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
password: ['', [Validators.required, this.uppercaseValidator]]
});
}
uppercaseValidator(control) {
const hasUppercase = /[A-Z]/.test(control.value);
return hasUppercase ? null : { pattern: true };
}
}
85. How do you use Angular's `AsyncValidator` for asynchronous validation?
Asynchronous validators are used to perform validation that requires an HTTP request or other async operations.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, AsyncValidatorFn, AbstractControl } from '@angular/forms';
import { Observable, of } from 'rxjs';
import { debounceTime, map, catchError } from 'rxjs/operators';
@Component({
selector: 'app-async-validator',
template: `
`,
})
export class AsyncValidatorComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
username: ['', null, this.usernameValidator()]
});
}
usernameValidator(): AsyncValidatorFn {
return (control: AbstractControl): Observable => {
return of(control.value).pipe(
debounceTime(300),
map(value => value === 'admin' ? { taken: true } : null),
catchError(() => of(null))
);
};
}
}
86. How do you use Angular's `HttpClient` to make HTTP requests?
The `HttpClient` service is used to perform HTTP requests.
import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-http', template: `
Data: {{ data | json }}`, }) export class HttpComponent implements OnInit { data: any; constructor(private http: HttpClient) {} ngOnInit() { this.http.get('https://api.example.com/data').subscribe(response => { this.data = response; }); } }
87. How do you use Angular's `HttpInterceptor` to modify HTTP requests?
The `HttpInterceptor` allows you to intercept and modify HTTP requests and responses.
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler): Observable> {
const cloned = req.clone({
setHeaders: {
Authorization: 'Bearer my-token'
}
});
return next.handle(cloned);
}
}
88. How do you use Angular's `HttpParams` to build query parameters?
The `HttpParams` class is used to build query parameters for HTTP requests.
import { Component, OnInit } from '@angular/core'; import { HttpClient, HttpParams } from '@angular/common/http'; @Component({ selector: 'app-http-params', template: `
Data: {{ data | json }}`, }) export class HttpParamsComponent implements OnInit { data: any; constructor(private http: HttpClient) {} ngOnInit() { const params = new HttpParams().set('param1', 'value1').set('param2', 'value2'); this.http.get('https://api.example.com/data', { params }).subscribe(response => { this.data = response; }); } }
89. How do you use Angular's `NgModel` for two-way data binding?
The `NgModel` directive is used for two-way data binding in Angular forms.
import { Component } from '@angular/core'; @Component({ selector: 'app-ng-model', template: `
Name: {{ name }}`, }) export class NgModelComponent { name: string = ''; }
90. How do you use Angular's `Custom Pipe` to transform data?
Custom pipes allow you to transform data before displaying it in the template.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'reverse'
})
export class ReversePipe implements PipeTransform {
transform(value: string): string {
return value.split('').reverse().join('');
}
}
91. How do you use Angular's `@HostListener` to listen to DOM events?
The `@HostListener` decorator allows you to listen to DOM events in your component or directive.
import { Directive, HostListener } from '@angular/core';
@Directive({
selector: '[appHover]'
})
export class HoverDirective {
@HostListener('mouseenter') onMouseEnter() {
console.log('Mouse entered');
}
@HostListener('mouseleave') onMouseLeave() {
console.log('Mouse left');
}
}
92. How do you use Angular's `@ContentChild` to access projected content?
The `@ContentChild` decorator is used to access a single child element projected into a component.
import { Component, ContentChild, AfterContentInit, ElementRef } from '@angular/core';
@Component({
selector: 'app-content-child',
template: ` `,
})
export class ContentChildComponent implements AfterContentInit {
@ContentChild('content') content: ElementRef;
ngAfterContentInit() {
console.log(this.content.nativeElement.textContent);
}
}
93. How do you use Angular's `ChangeDetectorRef` to manually trigger change detection?
The `ChangeDetectorRef` service allows you to manually trigger change detection.
import { Component, ChangeDetectorRef } from '@angular/core'; @Component({ selector: 'app-detection', template: `
{{ message }}`, }) export class DetectionComponent { message: string = 'Initial Message'; constructor(private cd: ChangeDetectorRef) {} updateMessage() { this.message = 'Updated Message'; this.cd.detectChanges(); } }
94. How do you use Angular's `@Injectable` decorator to create a service?
The `@Injectable` decorator is used to create a service that can be injected into other components or services.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class DataService {
getData() {
return ['Item1', 'Item2', 'Item3'];
}
}
95. How do you use Angular's `@NgModule` to configure providers?
Providers can be configured in the `@NgModule` decorator to be available throughout the application or module.
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { DataService } from './data.service';
@NgModule({
imports: [CommonModule],
providers: [DataService]
})
export class SharedModule { }
96. How do you use Angular's `ng-content` to project content into a component?
The `ng-content` directive is used to project content into a component's template.
import { Component } from '@angular/core';
@Component({
selector: 'app-content',
template: ` `,
})
export class ContentComponent { }
97. How do you use Angular's `@Inject` decorator for dependency injection?
The `@Inject` decorator allows you to specify a dependency to be injected into a component or service.
import { Component, Inject } from '@angular/core'; import { DOCUMENT } from '@angular/common'; @Component({ selector: 'app-doc', template: `
Document title: {{ title }}`, }) export class DocComponent { title: string; constructor(@Inject(DOCUMENT) private document: Document) { this.title = this.document.title; } }
98. How do you use Angular's `@HostBinding` to bind properties to a host element?
The `@HostBinding` decorator is used to bind properties to the host element of a directive or component.
import { Directive, HostBinding } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
@HostBinding('class.highlighted') isHighlighted = true;
}
99. How do you use Angular's `@Host` decorator for dependency injection?
The `@Host` decorator allows you to inject a dependency from the host element.
import { Directive, Host } from '@angular/core';
import { DataService } from './data.service';
@Directive({
selector: '[appHost]',
})
export class HostDirective {
constructor(@Host() private dataService: DataService) {
console.log(this.dataService.getData());
}
}
100. How do you use Angular's `ngOnInit` lifecycle hook?
The `ngOnInit` lifecycle hook is used to perform initialization logic after Angular has initialized the component's data-bound properties.
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-init', template: `
Component initialized`, }) export class InitComponent implements OnInit { ngOnInit() { console.log('Component initialized'); } }
Intermediate Angular Questions - Part 6
101. How do you use Angular's `ngOnDestroy` lifecycle hook to clean up resources?
The `ngOnDestroy` lifecycle hook is used to perform cleanup just before Angular destroys the component or directive.
import { Component, OnDestroy } from '@angular/core'; import { Subscription } from 'rxjs'; @Component({ selector: 'app-destroy', template: `
Component is being destroyed`, }) export class DestroyComponent implements OnDestroy { private subscription: Subscription = new Subscription(); ngOnDestroy() { this.subscription.unsubscribe(); } }
102. How do you use Angular's `@ViewChild` to access a child component or element?
The `@ViewChild` decorator allows you to access a child component or element within the parent component.
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core'; @Component({ selector: 'app-view-child', template: `
Some text`, }) export class ViewChildComponent implements AfterViewInit { @ViewChild('paragraph') paragraph: ElementRef; ngAfterViewInit() { console.log(this.paragraph.nativeElement.textContent); } }
103. How do you use Angular's `@ContentChildren` to access multiple projected content elements?
The `@ContentChildren` decorator is used to access multiple child elements projected into a component.
import { Component, ContentChildren, QueryList, AfterContentInit, ElementRef } from '@angular/core';
@Component({
selector: 'app-content-children',
template: ` `,
})
export class ContentChildrenComponent implements AfterContentInit {
@ContentChildren('content') contents: QueryList;
ngAfterContentInit() {
this.contents.forEach(content => {
console.log(content.nativeElement.textContent);
});
}
}
104. How do you use Angular's `ngOnChanges` lifecycle hook to respond to input property changes?
The `ngOnChanges` lifecycle hook allows you to respond to changes in input properties.
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core'; @Component({ selector: 'app-changes', template: `
{{ value }}`, }) export class ChangesComponent implements OnChanges { @Input() value: string; ngOnChanges(changes: SimpleChanges) { console.log('Changes:', changes); } }
105. How do you use Angular's `ngFor` to loop through an array in a template?
The `ngFor` directive is used to iterate over arrays or collections in Angular templates.
import { Component } from '@angular/core';
@Component({
selector: 'app-ng-for',
template: `
{{ item }}
`,
})
export class NgForComponent {
items = ['Item 1', 'Item 2', 'Item 3'];
}
106. How do you use Angular's `ngIf` to conditionally display elements?
The `ngIf` directive conditionally includes or excludes elements from the DOM.
import { Component } from '@angular/core'; @Component({ selector: 'app-ng-if', template: `This is visible`, }) export class NgIfComponent { isVisible = true; }
107. How do you use Angular's `ngClass` to apply CSS classes conditionally?
The `ngClass` directive is used to dynamically add or remove CSS classes based on expressions.
import { Component } from '@angular/core'; @Component({ selector: 'app-ng-class', template: `Conditional classes`, }) export class NgClassComponent { isActive = true; }
108. How do you use Angular's `ngStyle` to apply inline styles conditionally?
The `ngStyle` directive allows you to apply inline styles conditionally based on expressions.
import { Component } from '@angular/core'; @Component({ selector: 'app-ng-style', template: `Styled text`, }) export class NgStyleComponent { color = 'blue'; fontSize = '20px'; }
109. How do you use Angular's `@Pipe` to create a custom pipe?
The `@Pipe` decorator is used to create custom pipes to transform data in templates.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'uppercase'
})
export class UppercasePipe implements PipeTransform {
transform(value: string): string {
return value.toUpperCase();
}
}
110. How do you use Angular's `ngModel` with two-way data binding in a form?
The `ngModel` directive is used for two-way data binding in Angular forms.
import { Component } from '@angular/core'; @Component({ selector: 'app-ng-model', template: `
Name: {{ name }}`, }) export class NgModelComponent { name: string = ''; }
111. How do you use Angular's `ReactiveForms` to handle form submissions?
Reactive forms provide a way to handle form submissions with more control over validation and state.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'app-reactive-form',
template: `
`,
})
export class ReactiveFormComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
name: ['']
});
}
onSubmit() {
console.log(this.form.value);
}
}
112. How do you use Angular's `FormBuilder` to create a form group?
The `FormBuilder` service is used to create form groups in a reactive form.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'app-form-builder',
template: `
`,
})
export class FormBuilderComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
email: ['']
});
}
}
113. How do you use Angular's `HttpInterceptor` to intercept HTTP requests?
The `HttpInterceptor` interface allows you to intercept and modify HTTP requests and responses.
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler): Observable> {
const authReq = req.clone({
headers: req.headers.set('Authorization', 'Bearer my-token')
});
return next.handle(authReq);
}
}
114. How do you use Angular's `HttpClient` to handle errors in HTTP requests?
The `HttpClient` service provides methods to handle errors using RxJS operators.
import { Component } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { catchError } from 'rxjs/operators'; import { of } from 'rxjs'; @Component({ selector: 'app-http-error', template: `
Check console for errors`, }) export class HttpErrorComponent { constructor(private http: HttpClient) { this.http.get('https://api.example.com/data') .pipe(catchError(error => { console.error('Error occurred:', error); return of([]); })) .subscribe(response => { console.log(response); }); } }
115. How do you use Angular's `@Directive` to create a custom directive?
The `@Directive` decorator is used to create custom directives that can manipulate the DOM.
import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(private el: ElementRef, private renderer: Renderer2) {}
@HostListener('mouseenter') onMouseEnter() {
this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'yellow');
}
@HostListener('mouseleave') onMouseLeave() {
this.renderer.removeStyle(this.el.nativeElement, 'backgroundColor');
}
}
116. How do you use Angular's `Renderer2` to interact with the DOM?
The `Renderer2` service allows you to interact with the DOM in a safe way.
import { Directive, Renderer2, ElementRef } from '@angular/core';
@Directive({
selector: '[appColor]'
})
export class ColorDirective {
constructor(private el: ElementRef, private renderer: Renderer2) {
this.renderer.setStyle(this.el.nativeElement, 'color', 'blue');
}
}
117. How do you use Angular's `@ViewChildren` to query multiple elements or components?
The `@ViewChildren` decorator allows you to query and access multiple child elements or components.
import { Component, ViewChildren, QueryList, AfterViewInit, ElementRef } from '@angular/core'; @Component({ selector: 'app-view-children', template: `{{ i }}`, }) export class ViewChildrenComponent implements AfterViewInit { @ViewChildren('item') items: QueryList; ngAfterViewInit() { this.items.forEach(item => { console.log(item.nativeElement.textContent); }); } }
118. How do you use Angular's `@NgModule` to create feature modules?
Feature modules are created using the `@NgModule` decorator to group related components, directives, and services.
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FeatureComponent } from './feature.component';
@NgModule({
imports: [CommonModule],
declarations: [FeatureComponent],
exports: [FeatureComponent]
})
export class FeatureModule { }
119. How do you use Angular's `RouterModule` to configure routes?
The `RouterModule` is used to configure routes and navigation in an Angular application.
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home.component';
import { AboutComponent } from './about.component';
const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: '', redirectTo: '/home', pathMatch: 'full' }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
120. How do you use Angular's `ActivatedRoute` to get route parameters?
The `ActivatedRoute` service allows you to access route parameters in your component.
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-route-params', template: `
Route ID: {{ id }}`, }) export class RouteParamsComponent implements OnInit { id: string; constructor(private route: ActivatedRoute) {} ngOnInit() { this.route.paramMap.subscribe(params => { this.id = params.get('id'); }); } }
Intermediate Angular Questions - Part 7
121. How do you use Angular's `HttpClient` to send a POST request with JSON data?
The `HttpClient` service can send POST requests with JSON data using the `post` method.
import { Component } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-post-request', template: `
Check console for response`, }) export class PostRequestComponent { constructor(private http: HttpClient) { this.http.post('https://api.example.com/data', { key: 'value' }) .subscribe(response => { console.log(response); }); } }
122. How do you use Angular's `FormArray` to manage an array of form controls?
The `FormArray` class allows you to manage an array of form controls in a reactive form.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormArray } from '@angular/forms';
@Component({
selector: 'app-form-array',
template: `
`,
})
export class FormArrayComponent {
form: FormGroup;
get items() {
return this.form.get('items') as FormArray;
}
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
items: this.fb.array(['', '', ''])
});
}
}
123. How do you use Angular's `HttpParams` to add query parameters to an HTTP request?
The `HttpParams` class is used to construct query parameters for an HTTP request.
import { Component } from '@angular/core'; import { HttpClient, HttpParams } from '@angular/common/http'; @Component({ selector: 'app-http-params', template: `
Check console for response`, }) export class HttpParamsComponent { constructor(private http: HttpClient) { const params = new HttpParams().set('param1', 'value1').set('param2', 'value2'); this.http.get('https://api.example.com/data', { params }) .subscribe(response => { console.log(response); }); } }
124. How do you use Angular's `@HostBinding` to bind properties of the host element?
The `@HostBinding` decorator allows you to bind properties of the host element in a directive or component.
import { Directive, HostBinding } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
@HostBinding('class.highlighted') isHighlighted = true;
}
125. How do you use Angular's `@HostListener` to listen to events on the host element?
The `@HostListener` decorator allows you to listen to events on the host element in a directive or component.
import { Directive, HostListener } from '@angular/core';
@Directive({
selector: '[appHover]'
})
export class HoverDirective {
@HostListener('mouseenter') onMouseEnter() {
console.log('Mouse entered');
}
@HostListener('mouseleave') onMouseLeave() {
console.log('Mouse left');
}
}
126. How do you use Angular's `@Inject` to inject dependencies into a service?
The `@Inject` decorator is used to specify a dependency to be injected into a service or component.
import { Injectable, Inject } from '@angular/core';
import { MyService } from './my-service.service';
@Injectable({
providedIn: 'root'
})
export class MyComponentService {
constructor(@Inject(MyService) private myService: MyService) {}
}
127. How do you use Angular's `@Optional` to make dependency injection optional?
The `@Optional` decorator allows you to specify that a dependency is optional.
import { Injectable, Optional } from '@angular/core';
import { OptionalService } from './optional.service';
@Injectable({
providedIn: 'root'
})
export class MyService {
constructor(@Optional() private optionalService?: OptionalService) {}
}
128. How do you use Angular's `@Self` to specify that a dependency should be resolved from the same injector?
The `@Self` decorator ensures that a dependency is resolved from the same injector, not from parent injectors.
import { Injectable, Self } from '@angular/core';
import { MyService } from './my-service.service';
@Injectable({
providedIn: 'root'
})
export class AnotherService {
constructor(@Self() private myService: MyService) {}
}
129. How do you use Angular's `@Attribute` to access the value of an attribute on the host element?
The `@Attribute` decorator allows you to access the value of an attribute on the host element.
import { Directive, Attribute } from '@angular/core';
@Directive({
selector: '[appAttribute]'
})
export class AttributeDirective {
constructor(@Attribute('data-attribute') private dataAttribute: string) {
console.log(dataAttribute);
}
}
130. How do you use Angular's `NgModule` to declare and import modules?
The `@NgModule` decorator is used to declare and import modules in an Angular application.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
131. How do you use Angular's `@NgModule` to provide services at the module level?
The `providers` array in `@NgModule` allows you to specify services to be available at the module level.
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { MyService } from './my-service.service';
@NgModule({
declarations: [AppComponent],
imports: [],
providers: [MyService],
bootstrap: [AppComponent]
})
export class AppModule { }
132. How do you use Angular's `@Pipe` to create a custom pipe?
The `@Pipe` decorator is used to create custom pipes that can transform data in templates.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'reverse'
})
export class ReversePipe implements PipeTransform {
transform(value: string): string {
return value.split('').reverse().join('');
}
}
133. How do you use Angular's `@Injectable` to create a service?
The `@Injectable` decorator is used to define a service that can be injected into other components or services.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class MyService {
constructor() {}
}
134. How do you use Angular's `@Component` to create a reusable component?
The `@Component` decorator is used to define a reusable component in Angular.
import { Component } from '@angular/core'; @Component({ selector: 'app-reusable', template: `
This is a reusable component`, }) export class ReusableComponent {}
135. How do you use Angular's `@ViewChild` to access a child component?
The `@ViewChild` decorator allows you to access and manipulate a child component or DOM element.
import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
selector: 'app-parent',
template: ` `,
})
export class ParentComponent implements AfterViewInit {
@ViewChild(ChildComponent) child: ChildComponent;
ngAfterViewInit() {
console.log(this.child);
}
}
136. How do you use Angular's `@ContentChild` to access content projected into a component?
The `@ContentChild` decorator allows you to access and manipulate content projected into a component.
import { Component, ContentChild, AfterContentInit, ElementRef } from '@angular/core';
@Component({
selector: 'app-content',
template: ` `,
})
export class ContentComponent implements AfterContentInit {
@ContentChild('content') content: ElementRef;
ngAfterContentInit() {
console.log(this.content.nativeElement.textContent);
}
}
137. How do you use Angular's `@NgModule` to export components from a module?
The `exports` array in `@NgModule` allows you to specify which components, directives, and pipes should be available to other modules.
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SharedComponent } from './shared.component';
@NgModule({
imports: [CommonModule],
declarations: [SharedComponent],
exports: [SharedComponent]
})
export class SharedModule { }
138. How do you use Angular's `@Inject` to provide a specific token value?
The `@Inject` decorator allows you to provide a specific token value for dependency injection.
import { Injectable, Inject, InjectionToken } from '@angular/core';
export const API_URL = new InjectionToken('apiUrl');
@Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(@Inject(API_URL) private apiUrl: string) {
console.log(apiUrl);
}
}
139. How do you use Angular's `@Directive` to create a structural directive?
The `@Directive` decorator is used to create a structural directive that can change the layout of the DOM.
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
@Directive({
selector: '[appIf]'
})
export class IfDirective {
constructor(private templateRef: TemplateRef, private viewContainer: ViewContainerRef) {}
@Input() set appIf(condition: boolean) {
if (condition) {
this.viewContainer.createEmbeddedView(this.templateRef);
} else {
this.viewContainer.clear();
}
}
}
140. How do you use Angular's `@NgModule` to configure providers with `forRoot` and `forChild`?
The `forRoot` and `forChild` methods are used to configure providers for root and feature modules, respectively.
import { NgModule, ModuleWithProviders } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MyService } from './my-service.service';
@NgModule({
imports: [CommonModule],
declarations: [],
exports: []
})
export class FeatureModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: FeatureModule,
providers: [MyService]
};
}
}
Intermediate Angular Questions - Part 8
141. How do you use Angular's `BehaviorSubject` for state management?
The `BehaviorSubject` is used to manage state in Angular. It holds the current value and emits it to new subscribers.
import { BehaviorSubject } from 'rxjs';
export class StateService {
private stateSubject = new BehaviorSubject(0);
state$ = this.stateSubject.asObservable();
updateState(value: number) {
this.stateSubject.next(value);
}
}
142. How do you implement Angular's `OnPush` change detection strategy?
The `OnPush` strategy improves performance by only checking for changes when the input properties change or when an event occurs.
import { Component, ChangeDetectionStrategy } from '@angular/core'; @Component({ selector: 'app-onpush', template: `
OnPush change detection`, changeDetection: ChangeDetectionStrategy.OnPush }) export class OnPushComponent {}
143. How do you use Angular's `@ViewEncapsulation` to control CSS encapsulation?
The `@ViewEncapsulation` decorator is used to control how styles are applied to components.
import { Component, ViewEncapsulation } from '@angular/core'; @Component({ selector: 'app-encapsulation', template: `
ViewEncapsulation example`, styles: [`p { color: red; }`], encapsulation: ViewEncapsulation.None }) export class EncapsulationComponent {}
144. How do you use Angular's `Route` with route guards?
Route guards control access to routes based on conditions.
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private router: Router) {}
canActivate(): boolean {
const isAuthenticated = false; // Replace with real authentication logic
if (isAuthenticated) {
return true;
} else {
this.router.navigate(['/login']);
return false;
}
}
}
145. How do you create a custom Angular pipe that accepts arguments?
Custom pipes can transform data based on provided arguments.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'multiply'
})
export class MultiplyPipe implements PipeTransform {
transform(value: number, multiplier: number): number {
return value * multiplier;
}
}
146. How do you use Angular's `FormBuilder` to create nested form groups?
The `FormBuilder` service can be used to create complex forms with nested form groups.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'app-nested-form',
template: `
`,
})
export class NestedFormComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
personalInfo: this.fb.group({
name: [''],
age: ['']
}),
address: this.fb.group({
street: [''],
city: ['']
})
});
}
}
147. How do you use Angular's `@NgModule` to configure lazy-loaded modules?
Lazy-loaded modules can be configured in the `@NgModule` using the `loadChildren` property in routes.
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [
{ path: 'lazy', loadChildren: () => import('./lazy/lazy.module').then(m => m.LazyModule) }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
148. How do you use Angular's `@NgModule` to provide a singleton service?
Providing a service in the `@NgModule` ensures that it is a singleton across the entire application.
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { MyService } from './my-service.service';
@NgModule({
declarations: [AppComponent],
imports: [],
providers: [MyService], // Singleton service
bootstrap: [AppComponent]
})
export class AppModule { }
149. How do you use Angular's `HttpInterceptor` to modify HTTP requests and responses?
The `HttpInterceptor` allows you to intercept and modify HTTP requests and responses.
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler): Observable> {
const clonedRequest = req.clone({
headers: req.headers.set('Authorization', 'Bearer token')
});
return next.handle(clonedRequest);
}
}
150. How do you use Angular's `ChangeDetectorRef` to manually trigger change detection?
The `ChangeDetectorRef` service allows you to manually trigger change detection in your components.
import { Component, ChangeDetectorRef } from '@angular/core'; @Component({ selector: 'app-manual-detect', template: `
Manual change detection`, }) export class ManualDetectComponent { constructor(private cdr: ChangeDetectorRef) {} triggerChangeDetection() { this.cdr.detectChanges(); } }
151. How do you use Angular's `Renderer2` to manipulate the DOM?
The `Renderer2` service provides methods to manipulate the DOM in a platform-independent way.
import { Directive, Renderer2, ElementRef } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(private renderer: Renderer2, private el: ElementRef) {
this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'yellow');
}
}
152. How do you use Angular's `NgFor` to iterate over an array of objects?
The `NgFor` directive is used to loop through an array of objects in the template.
import { Component } from '@angular/core';
@Component({
selector: 'app-item-list',
template: `
{{ item.name }}
`,
})
export class ItemListComponent {
items = [{ name: 'Item 1' }, { name: 'Item 2' }, { name: 'Item 3' }];
}
153. How do you use Angular's `NgIf` to conditionally render elements?
The `NgIf` directive allows you to conditionally include or exclude elements from the DOM.
import { Component } from '@angular/core'; @Component({ selector: 'app-conditional', template: `
This element is conditionally rendered`, }) export class ConditionalComponent { isVisible = true; }
154. How do you use Angular's `FormArray` to handle dynamic form controls?
The `FormArray` allows you to manage a dynamic list of form controls.
import { Component } from '@angular/core';
import { FormBuilder, FormArray, FormGroup } from '@angular/forms';
@Component({
selector: 'app-dynamic-form',
template: `
`,
})
export class DynamicFormComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
items: this.fb.array([])
});
}
get items() {
return this.form.get('items') as FormArray;
}
addItem() {
this.items.push(this.fb.control(''));
}
}
155. How do you use Angular's `@HostListener` to handle DOM events?
The `@HostListener` decorator allows you to listen to DOM events directly in your component.
import { Component, HostListener } from '@angular/core'; @Component({ selector: 'app-host-listener', template: `
HostListener example`, }) export class HostListenerComponent { @HostListener('click', ['$event']) onClick(event: Event) { console.log('Element clicked!', event); } }
156. How do you use Angular's `ngOnChanges` to respond to input property changes?
The `ngOnChanges` lifecycle hook is used to respond to changes in input properties.
import { Component, OnChanges, SimpleChanges, Input } from '@angular/core'; @Component({ selector: 'app-changes', template: `
ngOnChanges example`, }) export class ChangesComponent implements OnChanges { @Input() data: string; ngOnChanges(changes: SimpleChanges) { console.log('Changes detected:', changes); } }
157. How do you use Angular's `ngOnInit` to initialize component data?
The `ngOnInit` lifecycle hook is used to perform initialization tasks for the component.
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-init', template: `
ngOnInit example`, }) export class InitComponent implements OnInit { data: string; ngOnInit() { this.data = 'Initialized data'; } }
158. How do you use Angular's `ngOnDestroy` to clean up resources?
The `ngOnDestroy` lifecycle hook is used to perform cleanup tasks before the component is destroyed.
import { Component, OnDestroy } from '@angular/core'; import { Subscription } from 'rxjs'; @Component({ selector: 'app-destroy', template: `
ngOnDestroy example`, }) export class DestroyComponent implements OnDestroy { private subscription: Subscription; ngOnDestroy() { if (this.subscription) { this.subscription.unsubscribe(); } } }
159. How do you use Angular's `@Input` and `@Output` to communicate between parent and child components?
The `@Input` decorator allows a child component to receive data from a parent, while `@Output` allows the child to emit events to the parent.
import { Component, Input, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'app-child', template: ` `, }) export class ChildComponent { @Input() message: string; @Output() messageEvent = new EventEmitter(); sendMessage() { this.messageEvent.emit('Message from child'); } } @Component({ selector: 'app-parent', template: `
Received Message: {{ receivedMessage }}`, }) export class ParentComponent { parentMessage = 'Message from parent'; receivedMessage: string; receiveMessage(message: string) { this.receivedMessage = message; } }
160. How do you use Angular's `ngSwitch` to conditionally display elements based on a value?
The `ngSwitch` directive allows you to conditionally display elements based on a value.
import { Component } from '@angular/core'; @Component({ selector: 'app-switch', template: `
Value is A
Value is B
Default value`, }) export class SwitchComponent { value = 'A'; }
Intermediate Angular Questions - Part 9
161. How do you use Angular's `@Injectable` decorator to provide a service at a specific level?
The `@Injectable` decorator is used to mark a class as a service that can be injected. You can specify the provider in `@NgModule` or directly in the component.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root' // Singleton service provided at the root level
})
export class MyService {}
162. How do you use Angular's `@ContentChild` to access a child component projected into a content slot?
The `@ContentChild` decorator is used to access a child component or directive that is projected into a content slot.
import { Component, ContentChild, AfterContentInit } from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
selector: 'app-parent',
template: ` `
})
export class ParentComponent implements AfterContentInit {
@ContentChild(ChildComponent) child: ChildComponent;
ngAfterContentInit() {
console.log(this.child);
}
}
163. How do you use Angular's `@ViewChild` to access a child component within the view?
The `@ViewChild` decorator is used to access a child component or directive within the view.
import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
selector: 'app-parent',
template: ` `
})
export class ParentComponent implements AfterViewInit {
@ViewChild(ChildComponent) child: ChildComponent;
ngAfterViewInit() {
console.log(this.child);
}
}
164. How do you use Angular's `ngModel` to bind form controls to component properties?
The `ngModel` directive is used for two-way data binding with form controls.
import { Component } from '@angular/core'; @Component({ selector: 'app-model', template: `
{{ value }}` }) export class ModelComponent { value: string = ''; }
165. How do you use Angular's `AsyncPipe` to handle asynchronous data?
The `AsyncPipe` subscribes to an observable or promise and returns the latest value it has emitted.
import { Component } from '@angular/core'; import { Observable, of } from 'rxjs'; @Component({ selector: 'app-async', template: `
{{ data$ | async }}` }) export class AsyncComponent { data$: Observable= of('Hello World'); }
166. How do you use Angular's `ngClass` to apply dynamic CSS classes?
The `ngClass` directive allows you to dynamically add or remove CSS classes based on component state.
import { Component } from '@angular/core'; @Component({ selector: 'app-class', template: `Dynamic Class` }) export class ClassComponent { isActive = true; }
167. How do you use Angular's `ngStyle` to apply dynamic inline styles?
The `ngStyle` directive allows you to dynamically set inline styles on an element.
import { Component } from '@angular/core'; @Component({ selector: 'app-style', template: `Styled Text` }) export class StyleComponent { color = 'blue'; fontSize = '20px'; }
168. How do you use Angular's `ngFor` with a trackBy function to optimize rendering?
The `trackBy` function helps Angular optimize rendering by tracking items in a list.
import { Component } from '@angular/core';
@Component({
selector: 'app-trackby',
template: `
{{ item.name }}
`
})
export class TrackByComponent {
items = [{ id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2' }];
trackByFn(index: number, item: any) {
return item.id;
}
}
169. How do you use Angular's `ngIf` with `else` to conditionally render elements?
The `ngIf` directive can be used with `else` to display alternate content based on a condition.
import { Component } from '@angular/core'; @Component({ selector: 'app-if-else', template: `Visible ContentNot Visible Content ` }) export class IfElseComponent { isVisible = true; }
170. How do you use Angular's `@HostBinding` to bind properties to the host element?
The `@HostBinding` decorator allows you to bind properties to the host element of the directive or component.
import { Directive, HostBinding } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
@HostBinding('class.highlight') isHighlighted = true;
}
171. How do you use Angular's `@HostListener` to listen to events on the host element?
The `@HostListener` decorator allows you to listen to events on the host element of the directive or component.
import { Directive, HostListener } from '@angular/core';
@Directive({
selector: '[appClickTracker]'
})
export class ClickTrackerDirective {
@HostListener('click', ['$event'])
onClick(event: Event) {
console.log('Host element clicked!', event);
}
}
172. How do you use Angular's `HttpClient` to make HTTP requests?
The `HttpClient` service is used to make HTTP requests and handle responses.
import { HttpClient } from '@angular/common/http'; import { Component } from '@angular/core'; import { Observable } from 'rxjs'; @Component({ selector: 'app-http', template: `
Data: {{ data$ | async }}` }) export class HttpComponent { data$: Observable; constructor(private http: HttpClient) { this.data$ = this.http.get('https://api.example.com/data'); } }
173. How do you use Angular's `HttpInterceptor` to modify HTTP requests and responses?
The `HttpInterceptor` allows you to intercept and modify HTTP requests and responses.
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler): Observable> {
const clonedRequest = req.clone({
setHeaders: { Authorization: 'Bearer token' }
});
return next.handle(clonedRequest);
}
}
174. How do you use Angular's `Router` to navigate between routes programmatically?
The `Router` service is used to navigate between routes programmatically.
import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-navigate',
template: ``
})
export class NavigateComponent {
constructor(private router: Router) {}
goToPage() {
this.router.navigate(['/page']);
}
}
175. How do you use Angular's `ActivatedRoute` to access route parameters?
The `ActivatedRoute` service allows you to access route parameters and query parameters.
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-route', template: `
Param: {{ param }}` }) export class RouteComponent implements OnInit { param: string; constructor(private route: ActivatedRoute) {} ngOnInit() { this.route.params.subscribe(params => { this.param = params['id']; }); } }
176. How do you use Angular's `Route Guards` to protect routes?
Route guards are used to protect routes based on certain conditions.
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
constructor(private router: Router) {}
canActivate(): boolean {
const isAuthenticated = false; // Check authentication
if (!isAuthenticated) {
this.router.navigate(['/login']);
return false;
}
return true;
}
}
177. How do you use Angular's `RouterOutlet` to display routed components?
The `RouterOutlet` directive is used to display routed components based on the active route.
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AppComponent } from './app.component';
import { HomeComponent } from './home.component';
const routes: Routes = [
{ path: '', component: HomeComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
@Component({
selector: 'app-root',
template: ` `
})
export class AppComponent {}
178. How do you use Angular's `Dependency Injection` to inject services into components?
Dependency Injection is used to inject services into components or other services.
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class MyService {} import { Component } from '@angular/core'; import { MyService } from './my.service'; @Component({ selector: 'app-example', template: `
Service injected` }) export class ExampleComponent { constructor(private myService: MyService) {} }
179. How do you use Angular's `Custom Pipes` to transform data?
Custom pipes are used to transform data before displaying it in the template.
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'reverse' }) export class ReversePipe implements PipeTransform { transform(value: string): string { return value.split('').reverse().join(''); } } @Component({ selector: 'app-pipe', template: `
{{ 'Angular' | reverse }}` }) export class PipeComponent {}
180. How do you use Angular's `ChangeDetectionStrategy` to optimize change detection?
The `ChangeDetectionStrategy` is used to control how Angular checks for changes in a component.
import { Component, ChangeDetectionStrategy } from '@angular/core'; @Component({ selector: 'app-detection', template: `
Change Detection Strategy`, changeDetection: ChangeDetectionStrategy.OnPush }) export class DetectionComponent {}
Intermediate Angular Questions - Part 10
181. How do you use Angular's `@Inject` to inject dependencies?
The `@Inject` decorator is used to specify a provider to inject into a constructor when the dependency is not directly injectable.
import { Injectable, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';
@Injectable({
providedIn: 'root'
})
export class DocumentService {
constructor(@Inject(DOCUMENT) private document: Document) {}
}
182. How do you use Angular's `@Component` decorator to define component metadata?
The `@Component` decorator is used to define metadata for a component, such as its selector, template, and styles.
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent {}
183. How do you use Angular's `@NgModule` to define modules?
The `@NgModule` decorator defines an Angular module by providing metadata, such as declarations, imports, and providers.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
184. How do you use Angular's `ReactiveFormsModule` to build reactive forms?
The `ReactiveFormsModule` provides reactive form capabilities in Angular, allowing you to build and manage forms programmatically.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'app-reactive-form',
template: `
`
})
export class ReactiveFormComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
name: ['']
});
}
submit() {
console.log(this.form.value);
}
}
185. How do you use Angular's `FormsModule` to build template-driven forms?
The `FormsModule` provides support for template-driven forms in Angular, allowing you to build forms declaratively.
import { Component } from '@angular/core';
@Component({
selector: 'app-template-form',
template: `
`
})
export class TemplateFormComponent {
submit(form: any) {
console.log(form.value);
}
}
186. How do you use Angular's `HttpClient` with interceptors for logging?
Interceptors can be used with `HttpClient` to log HTTP requests and responses.
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class LoggingInterceptor implements HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler): Observable> {
console.log('Request made:', req);
return next.handle(req);
}
}
187. How do you use Angular's `@Output` to emit events from a child component?
The `@Output` decorator allows a child component to emit events to a parent component.
import { Component, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-child',
template: ``
})
export class ChildComponent {
@Output() notifyEvent = new EventEmitter();
notify() {
this.notifyEvent.emit();
}
}
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: ` `
})
export class ParentComponent {
onNotify() {
console.log('Notification received!');
}
}
188. How do you use Angular's `ng-template` to create reusable templates?
The `ng-template` directive allows you to define reusable templates that can be used with structural directives.
import { Component } from '@angular/core'; @Component({ selector: 'app-template', template: `
Hello, {{ name }}!` }) export class TemplateComponent {}
189. How do you use Angular's `ng-content` to project content into a component?
The `ng-content` directive is used to project content from a parent component into a child component.
import { Component } from '@angular/core'; @Component({ selector: 'app-child', template: `` }) export class ChildComponent {} import { Component } from '@angular/core'; @Component({ selector: 'app-parent', template: `
Projected Content` }) export class ParentComponent {}
190. How do you use Angular's `Dynamic Component Loader` to load components dynamically?
The `ComponentFactoryResolver` allows you to dynamically create components at runtime.
import { Component, ComponentFactoryResolver, ViewChild, ViewContainerRef } from '@angular/core';
import { DynamicComponent } from './dynamic.component';
@Component({
selector: 'app-dynamic-loader',
template: ` `
})
export class DynamicLoaderComponent {
@ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef;
constructor(private resolver: ComponentFactoryResolver) {}
loadComponent() {
const factory = this.resolver.resolveComponentFactory(DynamicComponent);
this.container.createComponent(factory);
}
}
191. How do you use Angular's `FormArray` to manage dynamic form controls?
The `FormArray` is used to manage a collection of form controls, which can be dynamically added or removed.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormArray } from '@angular/forms';
@Component({
selector: 'app-dynamic-form',
template: `
`
})
export class DynamicFormComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
items: this.fb.array([])
});
}
get items() {
return this.form.get('items') as FormArray;
}
addItem() {
this.items.push(this.fb.control(''));
}
removeItem(index: number) {
this.items.removeAt(index);
}
}
192. How do you use Angular's `ChangeDetectorRef` to manually trigger change detection?
The `ChangeDetectorRef` service is used to manually trigger change detection in Angular.
import { Component, ChangeDetectorRef } from '@angular/core'; @Component({ selector: 'app-manual-detection', template: `
Manual Change Detection` }) export class ManualDetectionComponent { constructor(private cdr: ChangeDetectorRef) {} detectChanges() { this.cdr.detectChanges(); } }
193. How do you use Angular's `@HostListener` to listen to DOM events?
The `@HostListener` decorator allows you to listen to DOM events on the host element of a directive or component.
import { Directive, HostListener } from '@angular/core';
@Directive({
selector: '[appClickTracker]'
})
export class ClickTrackerDirective {
@HostListener('click', ['$event'])
onClick(event: Event) {
console.log('Element clicked!', event);
}
}
194. How do you use Angular's `@ViewChild` to access child components or elements?
The `@ViewChild` decorator allows you to access child components, directives, or DOM elements from the parent component.
import { Component, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-parent',
template: ` `
})
export class ParentComponent {
@ViewChild('child') child: ElementRef;
clickChild() {
console.log(this.child);
}
}
195. How do you use Angular's `@ContentChild` to access projected content?
The `@ContentChild` decorator allows you to access content projected into a component using `ng-content`.
import { Component, ContentChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-content',
template: ` `
})
export class ContentComponent {
@ContentChild('projectedContent') content: ElementRef;
ngAfterContentInit() {
console.log(this.content.nativeElement.textContent);
}
}
196. How do you use Angular's `NgZone` to manage change detection?
The `NgZone` service allows you to run code inside or outside Angular's zone, which affects change detection.
import { Component, NgZone } from '@angular/core'; @Component({ selector: 'app-zone', template: `
NgZone Example` }) export class ZoneComponent { constructor(private ngZone: NgZone) {} runOutsideAngular() { this.ngZone.runOutsideAngular(() => { console.log('Running outside Angular zone'); }); } }
197. How do you use Angular's `ViewEncapsulation` to control component styles?
The `ViewEncapsulation` enum controls how styles are applied to components.
import { Component, ViewEncapsulation } from '@angular/core'; @Component({ selector: 'app-encapsulation', template: `
View Encapsulation Example`, styles: [`p { color: blue; }`], encapsulation: ViewEncapsulation.Emulated }) export class EncapsulationComponent {}
198. How do you use Angular's `NgModule` to configure lazy-loaded modules?
Lazy-loaded modules are configured using `NgModule` and the `RouterModule.forRoot` method with the `loadChildren` property.
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [
{ path: 'lazy', loadChildren: () => import('./lazy/lazy.module').then(m => m.LazyModule) }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
199. How do you use Angular's `ChangeDetectionStrategy.OnPush` to optimize performance?
The `ChangeDetectionStrategy.OnPush` strategy optimizes performance by checking for changes only when input properties change or events occur.
import { Component, ChangeDetectionStrategy } from '@angular/core'; @Component({ selector: 'app-performance', template: `
OnPush Change Detection`, changeDetection: ChangeDetectionStrategy.OnPush }) export class PerformanceComponent {}
200. How do you use Angular's `ng-container` to conditionally render elements without adding extra DOM nodes?
The `ng-container` directive allows you to conditionally render elements without adding extra DOM nodes.
import { Component } from '@angular/core'; @Component({ selector: 'app-container', template: `
Conditionally Rendered Content` }) export class ContainerComponent { isVisible = true; }
Intermediate Angular Questions - Part 11
201. How do you use Angular's `@Injectable` decorator to create services?
The `@Injectable` decorator marks a class as a service that can be injected into other classes.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class DataService {
getData() {
return ['Data 1', 'Data 2', 'Data 3'];
}
}
202. How do you use Angular's `ngIf` to conditionally render elements?
The `ngIf` directive conditionally includes a template based on the value of an expression.
import { Component } from '@angular/core'; @Component({ selector: 'app-condition', template: `This content is visible` }) export class ConditionComponent { isVisible = true; }
203. How do you use Angular's `ngFor` to iterate over a list?
The `ngFor` directive is used to iterate over a list of items and render them in the template.
import { Component } from '@angular/core';
@Component({
selector: 'app-list',
template: `
{{ item }}
`
})
export class ListComponent {
items = ['Item 1', 'Item 2', 'Item 3'];
}
204. How do you use Angular's `ngSwitch` to conditionally display elements?
The `ngSwitch` directive allows you to display different templates based on a value.
import { Component } from '@angular/core'; @Component({ selector: 'app-switch', template: `Red colorBlue colorDefault color` }) export class SwitchComponent { color = 'blue'; }
205. How do you use Angular's `@ViewChild` to access child elements or components?
The `@ViewChild` decorator is used to get a reference to a child component or element in the template.
import { Component, ViewChild, ElementRef } from '@angular/core'; @Component({ selector: 'app-view-child', template: `
Child Paragraph` }) export class ViewChildComponent { @ViewChild('paragraph') paragraph: ElementRef; ngAfterViewInit() { console.log(this.paragraph.nativeElement.textContent); } }
206. How do you use Angular's `ngStyle` to apply dynamic styles?
The `ngStyle` directive allows you to apply dynamic styles to an element based on an expression.
import { Component } from '@angular/core'; @Component({ selector: 'app-style', template: `Styled Text` }) export class StyleComponent { color = 'red'; fontSize = 20; }
207. How do you use Angular's `ngClass` to conditionally apply CSS classes?
The `ngClass` directive allows you to conditionally apply one or more CSS classes to an element.
import { Component } from '@angular/core'; @Component({ selector: 'app-class', template: `Conditional Classes` }) export class ClassComponent { isActive = true; isDisabled = false; }
208. How do you use Angular's `@Input` to pass data from parent to child components?
The `@Input` decorator allows a child component to receive data from its parent component.
import { Component, Input } from '@angular/core'; @Component({ selector: 'app-child', template: `
Received: {{ data }}` }) export class ChildComponent { @Input() data: string; } import { Component } from '@angular/core'; @Component({ selector: 'app-parent', template: `` }) export class ParentComponent { parentData = 'Data from parent'; }
209. How do you use Angular's `@HostBinding` to bind properties to the host element?
The `@HostBinding` decorator allows you to bind properties to the host element of a directive or component.
import { Directive, HostBinding } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
@HostBinding('style.backgroundColor') backgroundColor = 'yellow';
}
210. How do you use Angular's `@HostListener` to listen to events on the host element?
The `@HostListener` decorator allows you to listen to events on the host element of a directive or component.
import { Directive, HostListener } from '@angular/core';
@Directive({
selector: '[appClickTracker]'
})
export class ClickTrackerDirective {
@HostListener('click', ['$event'])
onClick(event: Event) {
console.log('Element clicked:', event);
}
}
211. How do you use Angular's `Router` to navigate between different routes?
The `Router` service is used to navigate between different routes in an Angular application.
import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-navigation',
template: ``
})
export class NavigationComponent {
constructor(private router: Router) {}
navigate() {
this.router.navigate(['/details']);
}
}
212. How do you use Angular's `ActivatedRoute` to access route parameters?
The `ActivatedRoute` service is used to access route parameters and other information about the current route.
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-details', template: `
Item ID: {{ itemId }}` }) export class DetailsComponent implements OnInit { itemId: string; constructor(private route: ActivatedRoute) {} ngOnInit() { this.itemId = this.route.snapshot.paramMap.get('id'); } }
213. How do you use Angular's `RouterModule` to configure routes?
The `RouterModule` is used to configure application routes using the `RouterModule.forRoot` method.
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'about', component: AboutComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
214. How do you use Angular's `CanActivate` guard to protect routes?
The `CanActivate` guard is used to control access to routes based on conditions.
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private router: Router) {}
canActivate(): boolean {
const isAuthenticated = false; // Example condition
if (!isAuthenticated) {
this.router.navigate(['/login']);
return false;
}
return true;
}
}
215. How do you use Angular's `HttpClient` to make HTTP requests?
The `HttpClient` service is used to make HTTP requests and handle responses.
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class DataService {
constructor(private http: HttpClient) {}
getData() {
return this.http.get('https://api.example.com/data');
}
}
216. How do you use Angular's `HttpInterceptor` to modify HTTP requests and responses?
The `HttpInterceptor` interface allows you to intercept and modify HTTP requests and responses.
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler): Observable> {
const authReq = req.clone({ setHeaders: { Authorization: 'Bearer token' } });
return next.handle(authReq);
}
}
217. How do you use Angular's `FormBuilder` to create reactive forms?
The `FormBuilder` service simplifies the creation of reactive forms.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'app-reactive-form',
template: `
`
})
export class ReactiveFormComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
name: [''],
email: ['']
});
}
}
218. How do you use Angular's `FormArray` to manage an array of form controls?
The `FormArray` allows you to manage a collection of form controls.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormArray } from '@angular/forms';
@Component({
selector: 'app-dynamic-form',
template: `
`
})
export class DynamicFormComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
items: this.fb.array([])
});
}
get items() {
return this.form.get('items') as FormArray;
}
addItem() {
this.items.push(this.fb.control(''));
}
removeItem(index: number) {
this.items.removeAt(index);
}
}
219. How do you use Angular's `ngOnChanges` lifecycle hook to respond to input changes?
The `ngOnChanges` lifecycle hook responds to changes in input properties.
import { Component, OnChanges, SimpleChanges, Input } from '@angular/core'; @Component({ selector: 'app-changes', template: `
Previous: {{ prevValue }}, Current: {{ currentValue }}` }) export class ChangesComponent implements OnChanges { @Input() value: string; prevValue: string; currentValue: string; ngOnChanges(changes: SimpleChanges) { if (changes.value) { this.prevValue = changes.value.previousValue; this.currentValue = changes.value.currentValue; } } }
220. How do you use Angular's `ngAfterViewInit` lifecycle hook to perform actions after the view has been initialized?
The `ngAfterViewInit` lifecycle hook is used to perform actions after the view and child views have been initialized.
import { Component, AfterViewInit, ViewChild, ElementRef } from '@angular/core'; @Component({ selector: 'app-after-view', template: `
View Initialized` }) export class AfterViewComponent implements AfterViewInit { @ViewChild('paragraph') paragraph: ElementRef; ngAfterViewInit() { console.log(this.paragraph.nativeElement.textContent); } }
Intermediate Angular Questions - Part 12
221. How do you use Angular's `ng-content` to project content into a component?
The `ng-content` directive allows you to project content into a component's view.
import { Component } from '@angular/core'; @Component({ selector: 'app-card', template: `` }) export class CardComponent {}
import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: `
Card Title
Card content goes here.` }) export class AppComponent {}
222. How do you use Angular's `ng-template` to define reusable templates?
The `ng-template` directive defines reusable templates that can be instantiated later.
import { Component } from '@angular/core'; @Component({ selector: 'app-template', template: `
This is a reusable template.` }) export class TemplateComponent {}
223. How do you use Angular's `ChangeDetectionStrategy` to optimize change detection?
The `ChangeDetectionStrategy` can be set to `OnPush` to optimize change detection performance.
import { Component, ChangeDetectionStrategy } from '@angular/core'; @Component({ selector: 'app-optimized', template: `
Optimized Change Detection`, changeDetection: ChangeDetectionStrategy.OnPush }) export class OptimizedComponent {}
224. How do you use Angular's `Renderer2` to safely manipulate DOM elements?
The `Renderer2` service is used to safely manipulate DOM elements without direct access.
import { Component, ElementRef, Renderer2 } from '@angular/core'; @Component({ selector: 'app-renderer', template: `
Text` }) export class RendererComponent { constructor(private renderer: Renderer2, private el: ElementRef) {} ngAfterViewInit() { const paragraph = this.el.nativeElement.querySelector('p'); this.renderer.setStyle(paragraph, 'color', 'blue'); } }
225. How do you use Angular's `@Directive` to create custom directives?
The `@Directive` decorator is used to create custom directives that can modify the behavior of elements.
import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(private el: ElementRef, private renderer: Renderer2) {}
@HostListener('mouseenter') onMouseEnter() {
this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'yellow');
}
@HostListener('mouseleave') onMouseLeave() {
this.renderer.removeStyle(this.el.nativeElement, 'backgroundColor');
}
}
226. How do you use Angular's `@NgModule` to define modules and their dependencies?
The `@NgModule` decorator defines a module and its components, directives, and services.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { FeatureComponent } from './feature/feature.component';
@NgModule({
declarations: [
AppComponent,
FeatureComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
227. How do you use Angular's `Dependency Injection` to provide services?
Dependency Injection allows you to provide and inject services into components or other services.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class AuthService {
login() {
console.log('User logged in');
}
}
import { Component } from '@angular/core';
import { AuthService } from './auth.service';
@Component({
selector: 'app-login',
template: ``
})
export class LoginComponent {
constructor(private authService: AuthService) {}
login() {
this.authService.login();
}
}
228. How do you use Angular's `Observable` to handle asynchronous data streams?
The `Observable` class is used to handle asynchronous data streams and is often used with Angular's `HttpClient`.
import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; @Component({ selector: 'app-data', template: `
{{ data | json }}` }) export class DataComponent implements OnInit { data: any; constructor(private http: HttpClient) {} ngOnInit() { this.getData().subscribe(response => this.data = response); } getData(): Observable{ return this.http.get('https://api.example.com/data'); } }
229. How do you use Angular's `RxJS` operators to transform data streams?
RxJS operators are used to transform and manipulate data streams.
import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { map } from 'rxjs/operators'; @Component({ selector: 'app-transformed-data', template: `
{{ data | json }}` }) export class TransformedDataComponent implements OnInit { data: any; constructor(private http: HttpClient) {} ngOnInit() { this.getData().pipe( map(response => response.items) ).subscribe(items => this.data = items); } getData() { return this.http.get('https://api.example.com/data'); } }
230. How do you use Angular's `@Output` and `EventEmitter` to emit events from a child component?
The `@Output` decorator and `EventEmitter` are used to emit events from a child component to its parent.
import { Component, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-child',
template: ``
})
export class ChildComponent {
@Output() notifyEvent = new EventEmitter();
notify() {
this.notifyEvent.emit('Event from child');
}
}
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: ` `
})
export class ParentComponent {
handleNotification(message: string) {
console.log(message);
}
}
231. How do you use Angular's `@HostBinding` to bind host element properties?
The `@HostBinding` decorator allows you to bind properties of the host element.
import { Directive, HostBinding } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
@HostBinding('style.backgroundColor') backgroundColor: string = 'yellow';
}
232. How do you use Angular's `@HostListener` to listen to events on the host element?
The `@HostListener` decorator listens to events on the host element.
import { Directive, HostListener } from '@angular/core';
@Directive({
selector: '[appClickTracker]'
})
export class ClickTrackerDirective {
@HostListener('click', ['$event'])
onClick(event: MouseEvent) {
console.log('Element clicked:', event);
}
}
233. How do you use Angular's `ngFor` to loop through a collection of items?
The `ngFor` directive is used to loop through a collection and render each item.
import { Component } from '@angular/core';
@Component({
selector: 'app-list',
template: `
{{ item }}
`
})
export class ListComponent {
items: string[] = ['Item 1', 'Item 2', 'Item 3'];
}
234. How do you use Angular's `ngIf` to conditionally include or exclude elements?
The `ngIf` directive is used to conditionally include or exclude elements based on an expression.
import { Component } from '@angular/core'; @Component({ selector: 'app-conditional', template: `
This text is visible` }) export class ConditionalComponent { isVisible = true; }
235. How do you use Angular's `ngSwitch` to conditionally display elements?
The `ngSwitch` directive allows you to conditionally display elements based on a switch value.
import { Component } from '@angular/core'; @Component({ selector: 'app-switch', template: `
Red color
Green color
Default color` }) export class SwitchComponent { color = 'green'; }
236. How do you use Angular's `ngStyle` to dynamically set styles?
The `ngStyle` directive allows you to dynamically set CSS styles based on an object.
import { Component } from '@angular/core'; @Component({ selector: 'app-style', template: `Styled Div` }) export class StyleComponent { styles = { 'color': 'blue', 'font-size': '20px' }; }
237. How do you use Angular's `ngClass` to conditionally apply CSS classes?
The `ngClass` directive allows you to conditionally apply CSS classes based on an expression.
import { Component } from '@angular/core'; @Component({ selector: 'app-class', template: `Styled Div` }) export class ClassComponent { isActive = true; }
238. How do you use Angular's `ngModel` to bind form inputs to component properties?
The `ngModel` directive is used for two-way data binding between form inputs and component properties.
import { Component } from '@angular/core'; @Component({ selector: 'app-two-way-binding', template: `
Hello, {{ name }}!` }) export class TwoWayBindingComponent { name: string = ''; }
239. How do you use Angular's `FormControl` to manage individual form controls?
The `FormControl` class is used to manage the state and validation of individual form controls.
import { Component } from '@angular/core'; import { FormControl } from '@angular/forms'; @Component({ selector: 'app-form-control', template: `
Control Value: {{ nameControl.value }}` }) export class FormControlComponent { nameControl = new FormControl(''); }
240. How do you use Angular's `FormGroup` to manage a group of form controls?
The `FormGroup` class is used to group related `FormControl` instances into a single entity.
import { Component } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'app-form-group',
template: `
`
})
export class FormGroupComponent {
form = new FormGroup({
name: new FormControl(''),
email: new FormControl('')
});
}
Intermediate Angular Questions - Part 13
241. How do you use Angular's `@ViewChild` to access child components or DOM elements?
The `@ViewChild` decorator allows you to access child components or DOM elements from the parent component.
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core'; @Component({ selector: 'app-child', template: `
Child Component` }) export class ChildComponent {} @Component({ selector: 'app-parent', template: `` }) export class ParentComponent implements AfterViewInit { @ViewChild(ChildComponent) child!: ChildComponent; @ViewChild('childParagraph') childParagraph!: ElementRef; ngAfterViewInit() { console.log(this.child); console.log(this.childParagraph.nativeElement.textContent); } logChildParagraph() { console.log(this.childParagraph.nativeElement.textContent); } }
242. How do you use Angular's `@ContentChild` to access projected content?
The `@ContentChild` decorator allows you to access content projected into the component using `ng-content`.
import { Component, ContentChild, AfterContentInit, ElementRef } from '@angular/core'; @Component({ selector: 'app-card', template: `` }) export class CardComponent implements AfterContentInit { @ContentChild('cardContent') cardContent!: ElementRef; ngAfterContentInit() { console.log(this.cardContent.nativeElement.textContent); } } @Component({ selector: 'app-root', template: `
Card Content` }) export class AppComponent {}
243. How do you use Angular's `@Input` to pass data from a parent component to a child component?
The `@Input` decorator allows a parent component to pass data to a child component.
import { Component, Input } from '@angular/core'; @Component({ selector: 'app-child', template: `
Received: {{ data }}` }) export class ChildComponent { @Input() data!: string; } @Component({ selector: 'app-parent', template: `` }) export class ParentComponent { parentData = 'Data from Parent'; }
244. How do you use Angular's `@Output` to emit custom events from a child component?
The `@Output` decorator is used to create custom events that a child component can emit to its parent.
import { Component, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-child',
template: ``
})
export class ChildComponent {
@Output() message = new EventEmitter();
sendMessage() {
this.message.emit('Hello from Child');
}
}
@Component({
selector: 'app-parent',
template: ` `
})
export class ParentComponent {
receiveMessage(message: string) {
console.log(message);
}
}
245. How do you use Angular's `ReactiveForms` to create a form with validation?
The `ReactiveForms` module provides a way to create forms with validation using `FormGroup` and `FormControl`.
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'app-reactive-form',
template: `
`
})
export class ReactiveFormComponent {
form = new FormGroup({
name: new FormControl('', Validators.required)
});
onSubmit() {
console.log(this.form.value);
}
}
246. How do you use Angular's `ngFor` to display a list of items with a custom template?
The `ngFor` directive can be used with a custom template to display a list of items.
import { Component } from '@angular/core';
@Component({
selector: 'app-item-list',
template: `
{{ i + 1 }}. {{ item }}
`
})
export class ItemListComponent {
items = ['Item 1', 'Item 2', 'Item 3'];
}
247. How do you use Angular's `ngIf` with `else` to conditionally display content?
The `ngIf` directive can be used with the `else` clause to conditionally display alternate content.
import { Component } from '@angular/core'; @Component({ selector: 'app-conditional', template: `
Content is visible
Content is hidden` }) export class ConditionalComponent { isVisible = true; }
248. How do you use Angular's `ngSwitch` with multiple cases?
The `ngSwitch` directive can be used with multiple `ngSwitchCase` directives to handle different cases.
import { Component } from '@angular/core'; @Component({ selector: 'app-switch', template: `
Red
Green
Blue
Unknown color` }) export class SwitchComponent { color = 'green'; }
249. How do you use Angular's `ngStyle` to conditionally apply styles?
The `ngStyle` directive allows you to conditionally apply styles based on an object.
import { Component } from '@angular/core'; @Component({ selector: 'app-style', template: `Conditional Style` }) export class StyleComponent { isActive = true; }
250. How do you use Angular's `ngClass` to toggle multiple classes?
The `ngClass` directive allows you to toggle multiple CSS classes based on an object or array.
import { Component } from '@angular/core'; @Component({ selector: 'app-class', template: `Styled Div` }) export class ClassComponent { isActive = true; isHighlighted = false; }
251. How do you use Angular's `ngModel` with forms to manage user input?
The `ngModel` directive is used for two-way data binding in forms.
import { Component } from '@angular/core';
@Component({
selector: 'app-form',
template: `
`
})
export class FormComponent {
name = '';
}
252. How do you use Angular's `FormBuilder` to create reactive forms?
The `FormBuilder` service helps in creating `FormGroup` and `FormControl` instances more easily.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-form-builder',
template: `
`
})
export class FormBuilderComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
email: ['', Validators.required]
});
}
onSubmit() {
console.log(this.form.value);
}
}
253. How do you use Angular's `FormArray` to handle dynamic form fields?
The `FormArray` class is used to handle an array of form controls or groups.
import { Component } from '@angular/core';
import { FormBuilder, FormArray, FormGroup } from '@angular/forms';
@Component({
selector: 'app-form-array',
template: `
`
})
export class FormArrayComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
items: this.fb.array([''])
});
}
get items() {
return this.form.get('items') as FormArray;
}
addItem() {
this.items.push(this.fb.control(''));
}
}
254. How do you use Angular's `AsyncPipe` to handle asynchronous data?
The `AsyncPipe` subscribes to an observable or promise and returns the latest value.
import { Component } from '@angular/core'; import { Observable, of } from 'rxjs'; @Component({ selector: 'app-async', template: `{{ data }}` }) export class AsyncComponent { data$: Observable= of('Asynchronous Data'); }
255. How do you use Angular's `ChangeDetectionStrategy` to optimize change detection?
The `ChangeDetectionStrategy` can be set to `OnPush` to optimize change detection by checking only when input properties change.
import { Component, ChangeDetectionStrategy } from '@angular/core'; @Component({ selector: 'app-on-push', template: `
OnPush Change Detection`, changeDetection: ChangeDetectionStrategy.OnPush }) export class OnPushComponent {}
256. How do you use Angular's `@Injectable` to provide services in different scopes?
The `@Injectable` decorator is used to mark a class as available to be injected. Services can be provided at different levels, such as in the root or in a specific module.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root' // or provide in a specific module
})
export class DataService {
constructor() { }
}
257. How do you use Angular's `HttpClient` to make HTTP requests?
The `HttpClient` service is used to make HTTP requests and handle responses.
import { Component } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-http', template: `{{ data | json }}` }) export class HttpComponent { data: any; constructor(private http: HttpClient) { } fetchData() { this.http.get('https://api.example.com/data').subscribe(response => { this.data = response; }); } }
258. How do you use Angular's `Router` to navigate between routes?
The `Router` service is used to navigate between routes programmatically.
import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-navigation',
template: ``
})
export class NavigationComponent {
constructor(private router: Router) { }
goToHome() {
this.router.navigate(['/home']);
}
}
259. How do you use Angular's `ActivatedRoute` to access route parameters?
The `ActivatedRoute` service is used to access route parameters and query parameters.
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-route-params', template: `
Route Parameter: {{ id }}` }) export class RouteParamsComponent implements OnInit { id!: string; constructor(private route: ActivatedRoute) { } ngOnInit() { this.route.paramMap.subscribe(params => { this.id = params.get('id')!; }); } }
260. How do you use Angular's `RouterModule` to define and configure routes?
The `RouterModule` is used to define and configure routes in an Angular application.
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home.component';
import { AboutComponent } from './about.component';
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'about', component: AboutComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Angular Intermediate Level Questions - Part 15
261. How do you create an Angular pipe and use it?
An Angular pipe is used to transform data in templates. You create a pipe by using the `@Pipe` decorator.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'reverse'
})
export class ReversePipe implements PipeTransform {
transform(value: string): string {
return value.split('').reverse().join('');
}
}
262. How do you create a custom Angular validator?
Custom validators can be created by implementing the `Validator` interface or by creating a function that returns a validator function.
import { AbstractControl, ValidatorFn } from '@angular/forms';
export function forbiddenNameValidator(nameRe: RegExp): ValidatorFn {
return (control: AbstractControl): {[key: string]: any} | null => {
const forbidden = nameRe.test(control.value);
return forbidden ? { 'forbiddenName': { value: control.value } } : null;
};
}
263. How do you use Angular's `@HostBinding` and `@HostListener` decorators?
`@HostBinding` binds a property of the host element, while `@HostListener` listens to events on the host element.
import { Directive, HostBinding, HostListener } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
@HostBinding('style.backgroundColor') backgroundColor = 'transparent';
@HostListener('mouseenter') onMouseEnter() {
this.backgroundColor = 'yellow';
}
@HostListener('mouseleave') onMouseLeave() {
this.backgroundColor = 'transparent';
}
}
264. How do you use Angular's `ChangeDetectorRef` to manually trigger change detection?
`ChangeDetectorRef` is used to manually trigger change detection or detach the change detector.
import { ChangeDetectorRef, Component } from '@angular/core'; @Component({ selector: 'app-manual-change-detection', template: `
{{ data }}` }) export class ManualChangeDetectionComponent { data = 'Initial Data'; constructor(private cdr: ChangeDetectorRef) {} updateData() { this.data = 'Updated Data'; this.cdr.detectChanges(); // Manually trigger change detection } }
265. How do you use Angular's `ngOnDestroy` lifecycle hook?
The `ngOnDestroy` lifecycle hook is used to clean up resources before the component is destroyed.
import { Component, OnDestroy } from '@angular/core'; @Component({ selector: 'app-cleanup', template: `
Cleanup Component` }) export class CleanupComponent implements OnDestroy { ngOnDestroy() { console.log('CleanupComponent destroyed'); // Perform cleanup here } }
266. How do you use Angular's `@ViewChild` to access child components or elements?
`@ViewChild` allows you to access a child component or DOM element in the parent component class.
import { Component, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-parent',
template: ` `
})
export class ParentComponent {
@ViewChild('child') childComponent!: ElementRef;
ngAfterViewInit() {
console.log(this.childComponent.nativeElement);
}
}
267. How do you use Angular's `@ContentChild` to access projected content?
`@ContentChild` allows you to access projected content within a component.
import { Component, ContentChild, AfterContentInit, ElementRef } from '@angular/core';
@Component({
selector: 'app-content',
template: ` `
})
export class ContentComponent implements AfterContentInit {
@ContentChild('content') content!: ElementRef;
ngAfterContentInit() {
console.log(this.content.nativeElement.textContent);
}
}
268. How do you use Angular's `ngOnChanges` lifecycle hook?
The `ngOnChanges` lifecycle hook is used to detect changes to input properties.
import { Component, OnChanges, SimpleChanges, Input } from '@angular/core'; @Component({ selector: 'app-changes', template: `
Changes Component` }) export class ChangesComponent implements OnChanges { @Input() data!: string; ngOnChanges(changes: SimpleChanges) { console.log('Changes detected:', changes); } }
269. How do you use Angular's `ngSwitch` to conditionally display content?
The `ngSwitch` directive is used to conditionally display content based on a switch expression.
import { Component } from '@angular/core'; @Component({ selector: 'app-switch', template: `
Case A
Case B
Default Case` }) export class SwitchComponent { condition = 'A'; }
270. How do you use Angular's `ngClass` to apply multiple CSS classes dynamically?
The `ngClass` directive allows you to apply multiple CSS classes dynamically based on component data.
import { Component } from '@angular/core'; @Component({ selector: 'app-class', template: `Conditional Classes` }) export class ClassComponent { isActive = true; isHighlighted = false; }
271. How do you use Angular's `ng-template` to create reusable templates?
The `ng-template` directive allows you to define reusable templates.
import { Component } from '@angular/core'; @Component({ selector: 'app-template', template: `
This is a reusable template` }) export class TemplateComponent {}
272. How do you use Angular's `ngFor` with `trackBy` to improve performance?
The `trackBy` function helps Angular track items in a list for better performance.
import { Component } from '@angular/core';
@Component({
selector: 'app-for',
template: `
{{ item.name }}
`
})
export class ForComponent {
items = [{ id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2' }];
trackById(index: number, item: any): number {
return item.id;
}
}
273. How do you use Angular's `ngModel` with two-way data binding?
The `ngModel` directive provides two-way data binding for form elements.
import { Component } from '@angular/core'; @Component({ selector: 'app-model', template: `
Hello, {{ name }}!` }) export class ModelComponent { name = ''; }
274. How do you use Angular's `async` pipe in templates?
The `async` pipe subscribes to an Observable or Promise and returns the latest value.
import { Component } from '@angular/core'; import { Observable, of } from 'rxjs'; @Component({ selector: 'app-async', template: `{{ data }}` }) export class AsyncComponent { data$: Observable= of('Async Data'); }
275. How do you use Angular's `FormBuilder` to simplify form creation?
The `FormBuilder` service simplifies form creation with reactive forms.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'app-form-builder',
template: `
`
})
export class FormBuilderComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
name: ['']
});
}
submit() {
console.log(this.form.value);
}
}
276. How do you use Angular's `HttpInterceptor` to modify HTTP requests and responses?
`HttpInterceptor` allows you to intercept and modify HTTP requests and responses.
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler): Observable> {
const clonedReq = req.clone({ headers: req.headers.set('Authorization', 'Bearer token') });
return next.handle(clonedReq);
}
}
277. How do you use Angular's `Router` to navigate programmatically?
The `Router` service allows you to navigate programmatically within your application.
import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-navigate',
template: ``
})
export class NavigateComponent {
constructor(private router: Router) {}
goToHome() {
this.router.navigate(['/home']);
}
}
278. How do you use Angular's `ng-container` to group elements without affecting layout?
`ng-container` is a logical container that doesn't affect the DOM layout.
import { Component } from '@angular/core'; @Component({ selector: 'app-container', template: `
Content is visible` }) export class ContainerComponent { isVisible = true; }
279. How do you use Angular's `RouterModule` to configure routing?
The `RouterModule` is used to configure and manage routing in Angular applications.
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home.component';
import { AboutComponent } from './about.component';
const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: '', redirectTo: '/home', pathMatch: 'full' }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
280. How do you use Angular's `@Inject` to inject dependencies?
The `@Inject` decorator is used to specify a dependency to be injected.
import { Component, Inject } from '@angular/core'; @Component({ selector: 'app-inject', template: `
Inject Component` }) export class InjectComponent { constructor(@Inject('API_URL') private apiUrl: string) { console.log(apiUrl); } }
Angular Intermediate Level Questions - Part 16
281. How do you use Angular's `FormArray` to manage an array of form controls?
`FormArray` is used to manage an array of form controls in a reactive form.
import { Component } from '@angular/core';
import { FormBuilder, FormArray, FormGroup } from '@angular/forms';
@Component({
selector: 'app-form-array',
template: `
`
})
export class FormArrayComponent {
form: FormGroup;
get items(): FormArray {
return this.form.get('items') as FormArray;
}
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
items: this.fb.array([])
});
}
addItem() {
this.items.push(this.fb.control(''));
}
}
282. How do you use Angular's `@Optional` decorator to handle optional dependencies?
The `@Optional` decorator allows you to inject dependencies that may or may not be available.
import { Component, Optional } from '@angular/core'; @Component({ selector: 'app-optional', template: `
Optional Component` }) export class OptionalComponent { constructor(@Optional() private optionalService?: SomeService) { if (this.optionalService) { // Use the service } else { // Handle the absence of the service } } }
283. How do you use Angular's `NgZone` to run code inside or outside Angular's zone?
`NgZone` allows you to run code inside or outside Angular's change detection zone.
import { Component, NgZone } from '@angular/core'; @Component({ selector: 'app-zone', template: `
Zone Component` }) export class ZoneComponent { constructor(private ngZone: NgZone) { this.ngZone.runOutsideAngular(() => { // Code running outside Angular's zone console.log('Outside Angular Zone'); // Simulate an async operation setTimeout(() => { this.ngZone.run(() => { console.log('Back inside Angular Zone'); }); }, 1000); }); } }
284. How do you use Angular's `@Injectable` decorator with providedIn?
The `@Injectable` decorator with `providedIn` allows you to specify the provider scope for a service.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root' // Service is available throughout the app
})
export class MyService {
constructor() {}
}
285. How do you use Angular's `@ContentChildren` to access multiple projected content elements?
`@ContentChildren` is used to access multiple projected content elements.
import { Component, ContentChildren, QueryList, AfterContentInit, ElementRef } from '@angular/core';
@Component({
selector: 'app-content',
template: `
`
})
export class ContentComponent implements AfterContentInit {
@ContentChildren('content') contents!: QueryList;
ngAfterContentInit() {
this.contents.forEach(content => {
console.log(content.nativeElement.textContent);
});
}
}
286. How do you use Angular's `@Host` decorator to inject a dependency from the host element?
The `@Host` decorator allows you to inject a dependency from the host element.
import { Component, Host } from '@angular/core'; @Component({ selector: 'app-host', template: `
Host Component` }) export class HostComponent { constructor(@Host() private parentComponent: ParentComponent) { console.log(this.parentComponent); } }
287. How do you use Angular's `@Input` and `@Output` decorators to pass data between components?
`@Input` and `@Output` are used to pass data between parent and child components.
import { Component, Input, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'app-child', template: `
{{ data }}` }) export class ChildComponent { @Input() data!: string; @Output() dataChange = new EventEmitter(); sendData() { this.dataChange.emit('New Data'); } } @Component({ selector: 'app-parent', template: ` ` }) export class ParentComponent { parentData = 'Initial Data'; handleDataChange(newData: string) { this.parentData = newData; } }
288. How do you use Angular's `@Inject` decorator to inject tokens?
The `@Inject` decorator is used to inject tokens for dependency injection.
import { InjectionToken, Injectable, Inject } from '@angular/core';
export const API_URL = new InjectionToken('apiUrl');
@Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(@Inject(API_URL) private apiUrl: string) {
console.log(apiUrl);
}
}
289. How do you use Angular's `ngIf` with `else` to handle conditional templates?
`ngIf` with `else` allows you to handle conditional templates more elegantly.
import { Component } from '@angular/core'; @Component({ selector: 'app-if-else', template: `
Visible
Not Visible` }) export class IfElseComponent { isVisible = true; }
290. How do you use Angular's `ngFor` with `index` to display item indexes?
`ngFor` with `index` allows you to display the index of items in a list.
import { Component } from '@angular/core';
@Component({
selector: 'app-for-index',
template: `
{{ i + 1 }}. {{ item }}
`
})
export class ForIndexComponent {
items = ['Item 1', 'Item 2', 'Item 3'];
}
291. How do you use Angular's `@ViewChild` to access a child component or element?
`@ViewChild` allows you to access a child component or element in the template.
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core'; @Component({ selector: 'app-view-child', template: `Content` }) export class ViewChildComponent implements AfterViewInit { @ViewChild('content') content!: ElementRef; ngAfterViewInit() { console.log(this.content.nativeElement.textContent); } }
292. How do you use Angular's `ngClass` to conditionally apply CSS classes?
`ngClass` is used to conditionally apply CSS classes based on expressions.
import { Component } from '@angular/core'; @Component({ selector: 'app-class', template: `Conditional Classes` }) export class ClassComponent { isActive = true; }
293. How do you use Angular's `ngStyle` to apply inline styles dynamically?
`ngStyle` allows you to apply inline styles dynamically based on expressions.
import { Component } from '@angular/core'; @Component({ selector: 'app-style', template: `Dynamic Styles` }) export class StyleComponent { color = 'blue'; fontSize = 16; }
294. How do you use Angular's `@HostListener` to listen to DOM events?
The `@HostListener` decorator allows you to listen to DOM events on the host element.
import { Component, HostListener } from '@angular/core'; @Component({ selector: 'app-host-listener', template: `
Host Listener Component` }) export class HostListenerComponent { @HostListener('click', ['$event']) onClick(event: Event) { console.log('Element clicked', event); } }
295. How do you use Angular's `ChangeDetectorRef` to manually trigger change detection?
`ChangeDetectorRef` allows you to manually trigger change detection in Angular.
import { Component, ChangeDetectorRef } from '@angular/core'; @Component({ selector: 'app-change-detector', template: `
Change Detector Component` }) export class ChangeDetectorComponent { constructor(private cdr: ChangeDetectorRef) {} triggerChangeDetection() { this.cdr.detectChanges(); } }
296. How do you use Angular's `@Directive` to create a custom directive?
The `@Directive` decorator is used to create custom directives.
import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(private el: ElementRef, private renderer: Renderer2) {}
@HostListener('mouseenter') onMouseEnter() {
this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'yellow');
}
@HostListener('mouseleave') onMouseLeave() {
this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'transparent');
}
}
297. How do you use Angular's `@Pipe` to create a custom pipe?
The `@Pipe` decorator is used to create custom pipes.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'reverse'
})
export class ReversePipe implements PipeTransform {
transform(value: string): string {
return value.split('').reverse().join('');
}
}
298. How do you use Angular's `@NgModule` to define module metadata?
The `@NgModule` decorator is used to define the metadata for an Angular module.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
299. How do you use Angular's `Router` to define nested routes?
Nested routes can be defined using child routes in the Angular Router configuration.
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { ParentComponent } from './parent.component';
import { ChildComponent } from './child.component';
const routes: Routes = [
{ path: 'parent', component: ParentComponent, children: [
{ path: 'child', component: ChildComponent }
]}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
300. How do you use Angular's `@NgModule` to import and export modules?
The `@NgModule` decorator allows you to import and export modules within your application.
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
@NgModule({
imports: [CommonModule, FormsModule],
exports: [CommonModule, FormsModule]
})
export class SharedModule {}
Angular Intermediate Level Questions - Part 17
301. How do you use Angular's `ngSwitch` directive to conditionally display content?
`ngSwitch` allows you to conditionally display content based on an expression.
import { Component } from '@angular/core'; @Component({ selector: 'app-switch', template: `
Red
Green
Default` }) export class SwitchComponent { color = 'green'; }
302. How do you use Angular's `ngIf` with `then` to handle conditional templates?
`ngIf` with `then` allows you to specify a template to display when the condition is true.
import { Component } from '@angular/core'; @Component({ selector: 'app-if-then', template: `
Visible
Not Visible` }) export class IfThenComponent { isVisible = true; }
303. How do you use Angular's `ngFor` to iterate over objects?
`ngFor` can be used to iterate over objects and access their properties.
import { Component } from '@angular/core';
@Component({
selector: 'app-for-object',
template: `
{{ key }}: {{ myObject[key] }}
`
})
export class ForObjectComponent {
myObject = { name: 'Alice', age: 30, city: 'New York' };
objectKeys(obj: any) {
return Object.keys(obj);
}
}
304. How do you use Angular's `@Injectable` decorator to create a service with a custom provider?
`@Injectable` can be used with custom providers to configure service injection.
import { Injectable, InjectionToken } from '@angular/core';
export const API_URL = new InjectionToken('apiUrl');
@Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(@Inject(API_URL) private apiUrl: string) {}
}
305. How do you use Angular's `@ViewChild` with static options to access child components?
`@ViewChild` with `static: true` allows access to child components before the view initialization.
import { Component, ViewChild, AfterViewInit, ElementRef } from '@angular/core'; @Component({ selector: 'app-static-view-child', template: `Static View Child Content` }) export class StaticViewChildComponent implements AfterViewInit { @ViewChild('content', { static: true }) content!: ElementRef; ngAfterViewInit() { console.log(this.content.nativeElement.textContent); } }
306. How do you use Angular's `@Output` with `EventEmitter` to emit custom events?
`@Output` with `EventEmitter` allows you to emit custom events from a child component.
import { Component, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'app-output', template: ` ` }) export class OutputComponent { @Output() notify = new EventEmitter(); notifyParent() { this.notify.emit('Hello from child!'); } } @Component({ selector: 'app-parent', template: `
{{ message }}` }) export class ParentComponent { message = ''; handleNotification(msg: string) { this.message = msg; } }
307. How do you use Angular's `NgModule` with lazy loading to load modules on demand?
Lazy loading is implemented using the `loadChildren` property in the route configuration.
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [
{ path: 'lazy', loadChildren: () => import('./lazy/lazy.module').then(m => m.LazyModule) }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
308. How do you use Angular's `NgZone` to manage change detection manually?
`NgZone` allows you to manage Angular's change detection manually.
import { Component, NgZone } from '@angular/core'; @Component({ selector: 'app-zone', template: `
Zone Component` }) export class ZoneComponent { constructor(private ngZone: NgZone) {} runOutsideAngular() { this.ngZone.runOutsideAngular(() => { // Code running outside Angular's zone console.log('Running outside Angular zone'); setTimeout(() => { this.ngZone.run(() => { console.log('Running inside Angular zone'); }); }, 1000); }); } }
309. How do you use Angular's `ChangeDetectorRef` to trigger change detection?
`ChangeDetectorRef` is used to manually trigger change detection.
import { Component, ChangeDetectorRef } from '@angular/core'; @Component({ selector: 'app-change-detector', template: `
Change Detector Component` }) export class ChangeDetectorComponent { constructor(private cdr: ChangeDetectorRef) {} triggerChangeDetection() { this.cdr.detectChanges(); } }
310. How do you use Angular's `@HostBinding` to bind properties to the host element?
`@HostBinding` allows you to bind properties to the host element of a directive or component.
import { Directive, HostBinding } from '@angular/core';
@Directive({
selector: '[appHostBinding]'
})
export class HostBindingDirective {
@HostBinding('class.active') isActive = true;
}
311. How do you use Angular's `@HostListener` to listen to events on the host element?
`@HostListener` is used to listen to events on the host element.
import { Directive, HostListener } from '@angular/core';
@Directive({
selector: '[appHostListener]'
})
export class HostListenerDirective {
@HostListener('click', ['$event'])
onClick(event: Event) {
console.log('Host element clicked', event);
}
}
312. How do you use Angular's `@Input` and `@Output` decorators together to pass data between components?
`@Input` is used to pass data to a child component, while `@Output` is used to emit events from the child component.
import { Component, Input, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'app-child', template: `
{{ data }}` }) export class ChildComponent { @Input() data!: string; @Output() notify = new EventEmitter(); notifyParent() { this.notify.emit(); } } @Component({ selector: 'app-parent', template: `
{{ message }}` }) export class ParentComponent { parentData = 'Data from parent'; message = ''; handleNotification() { this.message = 'Child component notified!'; } }
313. How do you use Angular's `Router` to handle route parameters?
The `Router` allows you to handle route parameters using route configuration and activated route service.
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-route-param', template: `
Route Param: {{ id }}` }) export class RouteParamComponent implements OnInit { id!: string; constructor(private route: ActivatedRoute) {} ngOnInit() { this.route.paramMap.subscribe(params => { this.id = params.get('id') || ''; }); } } import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { RouteParamComponent } from './route-param.component'; const routes: Routes = [ { path: 'param/:id', component: RouteParamComponent } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule {}
314. How do you use Angular's `Router` to define route guards?
Route guards are used to control access to routes based on conditions.
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private router: Router) {}
canActivate(): boolean {
const isLoggedIn = false; // Replace with real authentication check
if (!isLoggedIn) {
this.router.navigate(['/login']);
return false;
}
return true;
}
}
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AuthGuard } from './auth.guard';
import { HomeComponent } from './home.component';
import { LoginComponent } from './login.component';
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'login', component: LoginComponent },
{ path: 'protected', component: ProtectedComponent, canActivate: [AuthGuard] }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
315. How do you use Angular's `NgModule` to define module dependencies?
Module dependencies are defined using the `imports` array in the `@NgModule` decorator.
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
@NgModule({
imports: [CommonModule, FormsModule],
declarations: [SomeComponent],
exports: [SomeComponent]
})
export class SomeModule {}
316. How do you use Angular's `@Component` decorator to configure component metadata?
The `@Component` decorator is used to configure metadata such as selector, template, and styles.
import { Component } from '@angular/core'; @Component({ selector: 'app-example', template: `
Example Component`, styles: [`p { color: blue; }`] }) export class ExampleComponent {}
317. How do you use Angular's `@NgModule` to create a feature module?
A feature module is created using `@NgModule` to group related components, directives, and services.
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FeatureComponent } from './feature.component';
@NgModule({
imports: [CommonModule],
declarations: [FeatureComponent],
exports: [FeatureComponent]
})
export class FeatureModule {}
318. How do you use Angular's `@Inject` to inject dependencies into a service?
`@Inject` is used to specify a custom provider for dependency injection.
import { Injectable, Inject } from '@angular/core';
export const API_URL = new InjectionToken('apiUrl');
@Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(@Inject(API_URL) private apiUrl: string) {}
}
319. How do you use Angular's `@NgModule` to define module imports and providers?
Module imports and providers are defined using the `imports` and `providers` arrays in `@NgModule`.
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SomeService } from './some.service';
@NgModule({
imports: [CommonModule],
providers: [SomeService]
})
export class SharedModule {}
320. How do you use Angular's `@Component` to define component templates and styles?
The `@Component` decorator defines component templates and styles using `template` and `styles` properties.
import { Component } from '@angular/core'; @Component({ selector: 'app-example', template: `Hello World`, styles: [`div { color: red; }`] }) export class ExampleComponent {}
Angular Intermediate Level Questions - Part 18
321. How do you use Angular's `HttpClient` to make HTTP GET requests?
`HttpClient` is used to make HTTP GET requests and handle responses.
import { HttpClient } from '@angular/common/http'; import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-http-get', template: `
Data: {{ data | json }}` }) export class HttpGetComponent implements OnInit { data: any; constructor(private http: HttpClient) {} ngOnInit() { this.http.get('https://api.example.com/data').subscribe(response => { this.data = response; }); } }
322. How do you use Angular's `HttpClient` to make HTTP POST requests?
`HttpClient` is used to make HTTP POST requests to send data to the server.
import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';
@Component({
selector: 'app-http-post',
template: ``
})
export class HttpPostComponent {
constructor(private http: HttpClient) {}
sendData() {
const payload = { key: 'value' };
this.http.post('https://api.example.com/submit', payload).subscribe(response => {
console.log('Response:', response);
});
}
}
323. How do you use Angular's `HttpClient` to handle query parameters?
Query parameters can be handled using the `params` option in `HttpClient` methods.
import { HttpClient, HttpParams } from '@angular/common/http'; import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-http-params', template: `
Data: {{ data | json }}` }) export class HttpParamsComponent implements OnInit { data: any; constructor(private http: HttpClient) {} ngOnInit() { let params = new HttpParams().set('param1', 'value1'); this.http.get('https://api.example.com/data', { params }).subscribe(response => { this.data = response; }); } }
324. How do you use Angular's `HttpInterceptor` to add headers to HTTP requests?
`HttpInterceptor` allows you to modify HTTP requests and responses globally.
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler): Observable> {
const authReq = req.clone({
setHeaders: { Authorization: 'Bearer token' }
});
return next.handle(authReq);
}
}
325. How do you use Angular's `HttpClient` to handle HTTP errors?
Errors in HTTP requests can be handled using RxJS operators like `catchError`.
import { HttpClient } from '@angular/common/http'; import { Component } from '@angular/core'; import { catchError } from 'rxjs/operators'; import { of } from 'rxjs'; @Component({ selector: 'app-http-error', template: `
Error: {{ errorMessage }}` }) export class HttpErrorComponent { errorMessage: string = ''; constructor(private http: HttpClient) {} makeRequest() { this.http.get('https://api.example.com/data').pipe( catchError(error => { this.errorMessage = 'An error occurred!'; return of([]); }) ).subscribe(); } }
326. How do you use Angular's `NgForm` to handle form validation?
`NgForm` provides form validation and status management.
import { Component } from '@angular/core';
import { NgForm } from '@angular/forms';
@Component({
selector: 'app-form-validation',
template: `
`
})
export class FormValidationComponent {
onSubmit(form: NgForm) {
if (form.valid) {
console.log('Form Submitted!', form.value);
}
}
}
327. How do you use Angular's `FormBuilder` to create reactive forms?
`FormBuilder` is used to create reactive forms with validators.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-reactive-form',
template: `
`
})
export class ReactiveFormComponent {
myForm: FormGroup;
constructor(private fb: FormBuilder) {
this.myForm = this.fb.group({
name: ['', Validators.required]
});
}
onSubmit() {
if (this.myForm.valid) {
console.log('Form Submitted!', this.myForm.value);
}
}
}
328. How do you use Angular's `FormControl` to handle form fields?
`FormControl` is used to manage the value and validation of individual form fields.
import { Component } from '@angular/core'; import { FormControl } from '@angular/forms'; @Component({ selector: 'app-form-control', template: `
Name is required` }) export class FormControlComponent { nameControl = new FormControl('', Validators.required); }
329. How do you use Angular's `FormArray` to handle dynamic form fields?
`FormArray` allows you to manage an array of form controls or groups dynamically.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormArray, Validators } from '@angular/forms';
@Component({
selector: 'app-form-array',
template: `
`
})
export class FormArrayComponent {
myForm: FormGroup;
get items() {
return this.myForm.get('items') as FormArray;
}
constructor(private fb: FormBuilder) {
this.myForm = this.fb.group({
items: this.fb.array([this.fb.control('', Validators.required)])
});
}
addItem() {
this.items.push(this.fb.control('', Validators.required));
}
onSubmit() {
if (this.myForm.valid) {
console.log('Form Submitted!', this.myForm.value);
}
}
}
330. How do you use Angular's `ngFor` directive to iterate over a list of items?
`ngFor` is used to iterate over a list and render a template for each item.
import { Component } from '@angular/core';
@Component({
selector: 'app-ng-for',
template: `
{{ item }}
`
})
export class NgForComponent {
items = ['Item 1', 'Item 2', 'Item 3'];
}
331. How do you use Angular's `ngIf` directive to conditionally render elements?
`ngIf` is used to conditionally include or exclude elements from the DOM.
import { Component } from '@angular/core'; @Component({ selector: 'app-ng-if', template: `Visible content` }) export class NgIfComponent { isVisible = true; toggleVisibility() { this.isVisible = !this.isVisible; } }
332. How do you use Angular's `ngSwitch` directive to conditionally render elements?
`ngSwitch` is used to conditionally include or exclude elements based on a switch expression.
import { Component } from '@angular/core'; @Component({ selector: 'app-ng-switch', template: `Option 1 contentOption 2 contentDefault content` }) export class NgSwitchComponent { selectedOption = 'option1'; selectOption(option: string) { this.selectedOption = option; } }
333. How do you use Angular's `ngClass` directive to conditionally apply CSS classes?
`ngClass` allows you to conditionally apply CSS classes to elements based on an expression.
import { Component } from '@angular/core'; @Component({ selector: 'app-ng-class', template: `Content`, styles: [` .active { color: green; } .inactive { color: red; } `] }) export class NgClassComponent { isActive = true; toggleStatus() { this.isActive = !this.isActive; } }
334. How do you use Angular's `ngStyle` directive to conditionally apply inline styles?
`ngStyle` allows you to conditionally apply inline styles to elements based on an expression.
import { Component } from '@angular/core'; @Component({ selector: 'app-ng-style', template: `Styled Content` }) export class NgStyleComponent { isActive = true; toggleStatus() { this.isActive = !this.isActive; } }
335. How do you use Angular's `ng-container` to group elements without adding extra DOM nodes?
`ng-container` is used to group elements and apply structural directives without adding extra DOM nodes.
import { Component } from '@angular/core'; @Component({ selector: 'app-ng-container', template: `
Visible Content 1
Visible Content 2` }) export class NgContainerComponent { isVisible = true; }
336. How do you use Angular's `ngModel` to two-way bind data?
`ngModel` provides two-way data binding between the view and the component.
import { Component } from '@angular/core'; @Component({ selector: 'app-ng-model', template: `
Data: {{ data }}` }) export class NgModelComponent { data = 'Initial value'; }
337. How do you use Angular's `@ViewChild` to access child components or DOM elements?
`@ViewChild` allows you to access child components or DOM elements directly from the parent component.
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core'; @Component({ selector: 'app-view-child', template: `Content` }) export class ViewChildComponent implements AfterViewInit { @ViewChild('myDiv') myDiv!: ElementRef; ngAfterViewInit() { console.log(this.myDiv.nativeElement.textContent); } changeContent() { this.myDiv.nativeElement.textContent = 'New Content'; } }
338. How do you use Angular's `@ContentChild` to access projected content?
`@ContentChild` allows you to access projected content inside a component.
import { Component, ContentChild, AfterContentInit, ElementRef } from '@angular/core'; @Component({ selector: 'app-content-child', template: `` }) export class ContentChildComponent implements AfterContentInit { @ContentChild('projectedContent') projectedContent!: ElementRef; ngAfterContentInit() { console.log(this.projectedContent.nativeElement.textContent); } } @Component({ selector: 'app-root', template: ` Projected Content` }) export class AppComponent {}
339. How do you use Angular's `@HostListener` to listen to DOM events?
`@HostListener` is used to listen to DOM events on the host element of the directive or component.
import { Directive, HostListener } from '@angular/core';
@Directive({
selector: '[appHostListener]'
})
export class HostListenerDirective {
@HostListener('click', ['$event'])
onClick(event: Event) {
console.log('Host element clicked', event);
}
}
340. How do you use Angular's `@Input` and `@Output` decorators together to pass data between components?
`@Input` is used to pass data to a child component, while `@Output` is used to emit events from the child component.
import { Component, Input, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'app-child', template: ` ` }) export class ChildComponent { @Input() data: string = ''; @Output() notify: EventEmitter= new EventEmitter (); notifyParent() { this.notify.emit(); } } @Component({ selector: 'app-parent', template: `
Received Data: {{ receivedData }}` }) export class ParentComponent { parentData = 'Data from parent'; receivedData = ''; handleNotification() { this.receivedData = 'Notification received from child!'; } }