Angular notes part 2 my notes
Features of Angular:
Angular is a TypeScript-based open-source web application framework developed by
Google. Its main features include:
1. Component-Based Architecture: UI is built using components, which are
reusable and encapsulated.
2. Two-Way Data Binding: Automatically syncs data between the model and the
view.
3. Dependency Injection (DI): Built-in DI system for better modularity and easier
testing.
4. Directives: Custom HTML behavior using built-in or custom directives (e.g.,
*ngIf, *ngFor).
5. Routing: Enables navigation between views/pages.
6. RxJS and Observables: For handling asynchronous operations.
7. Ahead-of-Time (AOT) Compilation: Improves performance by compiling during
build time.
8. TypeScript Support: Strongly typed language that helps catch errors at compile-
time.
9. Forms Management: Template-driven and reactive forms for handling user
input.
10. Testing: Support for unit and end-to-end testing (using Jasmine, Karma,
Protractor, etc.).
Angular Follows the MVC Pattern (Model-View-Controller):
Although Angular doesn't enforce traditional MVC strictly, it follows the MVVM (Model-
View-ViewModel) or component-based architecture, which is similar in spirit.
MVC Pattern in Angular - Simple Example:
Goal: Display a list of students and allow adding a new one.
Model (student.model.ts)
export interface Student {
id: number;
name: string;
Controller / Component (student.component.ts)
import { Component } from '@angular/core';
import { Student } from './student.model';
@Component({
selector: 'app-student',
templateUrl: './student.component.html'
})
export class StudentComponent {
students: Student[] = [
{ id: 1, name: 'Rakshitha' },
{ id: 2, name: 'Ankit' }
];
newStudent: string = '';
addStudent() {
if (this.newStudent.trim()) {
this.students.push({ id: this.students.length + 1, name: this.newStudent });
this.newStudent = '';
View (student.component.html)
<h2>Student List</h2>
<ul>
<li *ngFor="let student of students">{{ student.name }}</li>
</ul>
<input [(ngModel)]="newStudent" placeholder="Add student" />
<button (click)="addStudent()">Add</button>
Flow:
• Model: Holds data (Student object).
• View: HTML Template displaying the student list.
• Controller: Angular component managing logic and interaction between model
and view.
Would you like a working demo setup in StackBlitz or GitHub for practice?
Yes, Angular supports directives, and they are one of its core features.
What are Directives in Angular?
Directives are special markers in the DOM (like attributes or elements) that tell Angular
to do something with the element or its children.
Types of Directives:
1. Structural Directives
Change the structure of the DOM (e.g., adding/removing elements).
o Examples:
▪ *ngIf – Adds/removes element based on condition.
▪ *ngFor – Repeats an element for each item in a list.
▪ *ngSwitch – Conditional display with multiple cases.
Example:
<div *ngIf="isLoggedIn">Welcome, User!</div>
<ul>
<li *ngFor="let item of items">{{ item }}</li>
</ul>
2. Attribute Directives
Change the appearance or behavior of an element.
o Examples:
▪ ngClass – Add/remove CSS classes.
▪ ngStyle – Apply inline styles.
Example:
<p [ngStyle]="{'color': isError ? 'red' : 'green'}">Status Message</p>
3. Custom Directives
You can create your own directive to encapsulate reusable behavior.
Example (highlight.directive.ts):
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(private el: ElementRef) {}
@HostListener('mouseenter') onMouseEnter() {
this.el.nativeElement.style.backgroundColor = 'yellow';
@HostListener('mouseleave') onMouseLeave() {
this.el.nativeElement.style.backgroundColor = null;
Usage:
<p appHighlight>Hover me to see highlight</p>
Would you like help creating your own custom directive step-by-step?
Data Binding in Angular
Data binding is a core concept in Angular that enables communication between the
component class (TypeScript code) and the view (HTML template).
Types of Data Binding in Angular:
Type Direction Syntax Description
Component → Display data from
1. Interpolation {{ propertyName }}
Template component
2. Property Component → Bind DOM properties to
[property]="value"
Binding Template component
Template →
3. Event Binding (event)="handler()" Respond to user events
Component
4. Two-Way Sync input fields with
Both Ways [(ngModel)]="property"
Binding component
1. Interpolation Example:
<p>Hello, {{ userName }}!</p>
userName = 'Rakshitha';
2. Property Binding Example:
<img [src]="imageUrl" alt="Profile Picture">
imageUrl = 'assets/user.png';
3. Event Binding Example:
<button (click)="showMessage()">Click Me</button>
showMessage() {
alert('Button Clicked!');
4. Two-Way Binding Example (Requires FormsModule):
<input [(ngModel)]="name">
<p>Your name is: {{ name }}</p>
name = '';
Note: To use [(ngModel)], you must import FormsModule in your AppModule:
import { FormsModule } from '@angular/forms';
@NgModule({
imports: [ FormsModule ]
})
Certainly! Based on your request, here is a curated list of multiple-choice questions
(MCQs) covering various topics in Angular, TypeScript, RxJS, and related areas. These
questions are designed to test and reinforce your understanding of key concepts.
Angular MCQs
1. Which of the following is used to define a component in Angular?
• A) @Injectable
• B) @Directive
• C) @Component
• D) @NgModule
Answer: C) @Component
2. What is the purpose of Angular's ngFor directive?
• A) To conditionally display elements
• B) To apply styles dynamically
• C) To iterate over a list and render elements
• D) To handle form submissions
Answer: C) To iterate over a list and render elements
3. Which command is used to create a new Angular component using Angular CLI?
• A) ng create component
• B) ng generate component
• C) ng new component
• D) ng add component
Answer: B) ng generate component
4. In Angular, which symbol is used for property binding?
• A) ()
• B) []
• C) {{}}
• D) <>
Answer: B) []
5. What is the role of AppModule in an Angular application?
• A) It defines the root component
• B) It bootstraps the Angular application
• C) It configures the routing
• D) It handles HTTP requests
Answer: B) It bootstraps the Angular application
TypeScript MCQs
6. What is TypeScript primarily used for?
• A) Memory Management
• B) Dynamic Typing
• C) Static Typing
• D) Asynchronous operations
Answer: C) Static Typing
7. Which of the following is NOT a valid TypeScript data type?
• A) void
• B) any
• C) dynamic
• D) tuple
Answer: C) dynamic
8. How do you define a variable with a specific data type in TypeScript?
• A) let variable: type;
• B) variable = type;
• C) type variable;
• D) variable as type;
Answer: A) let variable: type;
9. What is the purpose of the enum keyword in TypeScript?
• A) To define a new data type
• B) To create a namespace
• C) To declare a variable
• D) To define a set of named constant values
Answer: D) To define a set of named constant values
10. What is the purpose of the never type in TypeScript?
• A) To represent a value that may be null or undefined
• B) To represent a function that never returns
• C) To declare a variable that cannot be reassigned
• D) To represent any type of value
Answer: B) To represent a function that never returns
RxJS MCQs
11. What does RxJS stand for?
• A) Reactive Extensions for JavaScript
• B) Reactive XML for JavaScript
• C) Regular Expressions for JavaScript
• D) None of the above
Answer: A) Reactive Extensions for JavaScript
12. Which RxJS operator is used to transform the items emitted by an Observable?
• A) filter
• B) map
• C) reduce
• D) scan
Answer: B) map
13. What is the purpose of the Subject in RxJS?
• A) To handle HTTP requests
• B) To multicast to multiple Observers
• C) To create a new Observable
• D) To perform side effects
Answer: B) To multicast to multiple Observers
14. Which operator is used to handle errors in RxJS?
• A) catchError
• B) retry
• C) throwError
• D) onErrorResumeNext
Answer: A) catchError
15. What does the switchMap operator do in RxJS?
• A) Maps each value to an Observable and flattens them in order
• B) Switches to a new Observable and cancels the previous one
• C) Maps each value to a Promise
• D) None of the above
Answer: B) Switches to a new Observable and cancels the previous one
Angular MCQs
1. Which decorator is used to define a component in Angular?
• A) @Injectable
• B) @Directive
• C) @Component
• D) @NgModule
Answer: C) @Component
2. What is the purpose of Angular's ngFor directive?
• A) To conditionally display elements
• B) To apply styles dynamically
• C) To iterate over a list and render elements
• D) To handle form submissions
Answer: C) To iterate over a list and render elements
3. Which command is used to create a new Angular component using Angular CLI?
• A) ng create component
• B) ng generate component
• C) ng new component
• D) ng add component
Answer: B) ng generate component
4. In Angular, which symbol is used for property binding?
• A) ()
• B) []
• C) {{}}
• D) <>
Answer: B) []
5. What is the role of AppModule in an Angular application?
• A) It defines the root component
• B) It bootstraps the Angular application
• C) It configures the routing
• D) It handles HTTP requests
Answer: B) It bootstraps the Angular application
6. Which of the following is used to define routes in Angular?
• A) app.module.ts
• B) app.component.ts
• C) angular.json
• D) app-routing.module.ts
Answer: D) app-routing.module.ts
7. What is the purpose of the @Injectable decorator in Angular?
• A) To define a component
• B) To define a directive
• C) To define a service that can be injected
• D) To define a module
Answer: C) To define a service that can be injected
8. Which directive is used to conditionally include a template in Angular?
• A) *ngFor
• B) *ngIf
• C) *ngSwitch
• D) *ngModel
Answer: B) *ngIf
9. What is the purpose of the ngClass directive in Angular?
• A) To apply styles dynamically
• B) To apply CSS classes dynamically
• C) To handle form submissions
• D) To define a component
Answer: B) To apply CSS classes dynamically
10. How do you bind an event in Angular?
• A) Using []
• B) Using ()
• C) Using {{}}
• D) Using <>
Answer: B) Using ()
TypeScript MCQs
11. What is TypeScript primarily used for?
• A) Memory Management
• B) Dynamic Typing
• C) Static Typing
• D) Asynchronous operations
Answer: C) Static Typing
12. Which of the following is NOT a valid TypeScript data type?
• A) void
• B) any
• C) dynamic
• D) tuple
Answer: C) dynamic
13. How do you define a variable with a specific data type in TypeScript?
• A) let variable: type;
• B) variable = type;
• C) type variable;
• D) variable as type;
Answer: A) let variable: type;
14. What is the purpose of the enum keyword in TypeScript?
• A) To define a new data type
• B) To create a namespace
• C) To declare a variable
• D) To define a set of named constant values
Answer: D) To define a set of named constant values
15. What is the purpose of the never type in TypeScript?
• A) To represent a value that may be null or undefined
• B) To represent a function that never returns
• C) To declare a variable that cannot be reassigned
• D) To represent any type of value
Answer: B) To represent a function that never returns
16. How is an optional parameter defined in a TypeScript function?
• A) By using the optional keyword
• B) By using the ? symbol after the parameter name
• C) By using the optional modifier
• D) By using the undefined keyword
Answer: B) By using the ? symbol after the parameter name
17. What is the purpose of the readonly modifier in TypeScript?
• A) To define a constant variable
• B) To declare a variable with a fixed size
• C) To prevent a variable from being reassigned
• D) To create a private variable
Answer: C) To prevent a variable from being reassigned
18. What is the purpose of the namespace keyword in TypeScript?
• A) To create a new class
• B) To define a block of code with its own scope
• C) To create a module
• D) To declare a global variable
Answer: C) To create a module
19. How can you define a tuple type in TypeScript?
• A) type MyTuple = array;
• B) type MyTuple = [number, string];
• C) type MyTuple = {number, string};
• D) type MyTuple = tuple;
Answer: B) type MyTuple = [number, string];
20. What is the difference between interface and type in TypeScript?
• A) interface is used for object shapes, type for aliases
• B) interface is used for aliases, type for object shapes
• C) Both are interchangeable
• D) None of the above
Answer: A) interface is used for object shapes, type for aliases
RxJS MCQs
21. What does RxJS stand for?
• A) Reactive Extensions for JavaScript
• B) Reactive XML for JavaScript
• C) Regular Expressions for JavaScript
• D) None of the above
Answer: A) Reactive Extensions for JavaScript
22. Which RxJS operator is used to transform the items emitted by an Observable?
• A) filter
• B) map
• C) reduce
• D) scan
Answer: B) map
23. What is the purpose of the Subject in RxJS?
• A) To handle HTTP requests
• B) To multicast to multiple Observers
• C) To create a new Observable
• D) To perform side effects
Answer: B) To multicast to multiple Observers
24. Which operator is used to handle errors in RxJS?
• A) catchError
• B) retry
• C) throwError
• D) onErrorResumeNext
Answer: A) catchError
25. What does the switchMap operator do in RxJS?
• A) Maps each value to an Observable and flattens them in order
• B) Switches to a new Observable and cancels the previous one
• C) Maps each value to a Promise
• D) None of the above
Answer: B) Switches to a new Observable and cancels the previous one
26. What are Observables in RxJS?
• A) Functions that emit values over time
• B) Static data structures
• C) Promises that resolve immediately
• D) None of the above
Answer: A) Functions that emit values over time
27. How can you unsubscribe from an Observable in RxJS?
• A) subscription.remove()
• B) subscription.unsubscribe()
• C) subscription.stop()
• D) subscription.cancel()
Answer: B) subscription.unsubscribe()
28. What is the role of schedulers in RxJS?
• A) To control when a subscription starts and when notifications are delivered
• B) To handle errors in Observables
• C) To manage memory leaks
• D) To create new Observables
Answer: A) To control when a subscription starts and when notifications are delivered
29. What is the purpose of the debounceTime operator in RxJS?
• A) To delay the emission of values
• B) To emit the first value and ignore subsequent ones
• C) To emit values at regular intervals
• D) To ignore values for a specified duration
Answer: A) To delay the emission of values
30. What is the difference between mergeMap and switchMap in RxJS?
• A) mergeMap cancels previous inner Observables, switchMap does not
• B) switchMap cancels previous inner Observables, mergeMap does not
• C) Both behave the same
• D) None of the above
Answer: B) switchMap cancels previous inner Observables, mergeMap does not
Sure! Here's the full list of Angular multiple-choice questions with their
respective options and answers listed after each question:
1. What is Angular primarily used for?
A. Game Development
B. Mobile App Development
C. Single Page Applications
D. Desktop Publishing
Answer: C
2. Which command is used to install Angular CLI globally?
A. npm install angular-cli
B. ng new
C. npm install -g @angular/cli
D. ng install cli
Answer: C
3. Which file contains the root module of an Angular application?
A. main.ts
B. index.html
C. app.module.ts
D. angular.json
Answer: C
4. What does the Angular CLI command ng generate component my-comp do?
A. Creates a module
B. Creates a new Angular project
C. Creates a component with boilerplate
D. Starts the Angular app
Answer: C
5. Which of the following is NOT a valid Angular decorator?
A. @Injectable()
B. @Pipe()
C. @Module()
D. @Component()
Answer: C
6. In Angular, which file contains application-wide configuration settings?
A. app.component.ts
B. main.ts
C. angular.json
D. styles.css
Answer: C
7. Which directive is used to display content conditionally?
A. *ngFor
B. *ngSwitch
C. *ngIf
D. *ngModel
Answer: C
8. Two-way binding in Angular is achieved using:
A. {{ }}
B. []
C. ()
D. [()]
Answer: D
9. Which binding type reflects the value from component to view only?
A. Two-way Binding
B. One-way Binding
C. Event Binding
D. None
Answer: B
10. Which CLI command is used to create a new Angular project?
A. ng init
B. ng generate
C. ng new
D. ng start
Answer: C
11. How do you include Bootstrap in your Angular project?
A. Manually include JS files
B. Install using npm and reference in angular.json
C. Use CDN in index.ts
D. Angular supports it natively
Answer: B
12. What is the purpose of AppModule in Angular?
A. It's the main component
B. It's the entry point of Angular app
C. It declares and bootstraps the application
D. It handles routing
Answer: C
13. Which decorator marks a class as an Angular Component?
A. @Injectable()
B. @NgModule()
C. @Directive()
D. @Component()
Answer: D
14. What is the use of @Input() in Angular?
A. Output data
B. Accept input from child component
C. Accept input from parent component
D. Provide dependency injection
Answer: C
15. What is used for outputting lists in Angular?
A. *ngSwitch
B. *ngList
C. *ngFor
D. *ngRepeat
Answer: C
16. Which lifecycle hook is called when the component is initialized?
A. ngAfterInit
B. ngOnInit
C. ngStart
D. constructor
Answer: B
17. What does @ViewChild() allow access to?
A. Parent component only
B. External APIs
C. DOM or component reference inside template
D. Services
Answer: C
18. What is the purpose of ng-content in Angular?
A. Binding events
B. Styling
C. Projecting content
D. Lifecycle management
Answer: C
19. Which type of directive is used to manipulate DOM structure?
A. Attribute directive
B. Structural directive
C. Service
D. Pipe
Answer: B
20. What Angular binding is used to bind events to methods?
A. []
B. ()
C. [()]
D. {{}}
Answer: B
21. What does @HostListener() do?
A. Style the host element
B. Listen to DOM events on host element
C. Define module routes
D. Provide a service
Answer: B
22. Which command serves your Angular app on localhost?
A. ng serve
B. ng start
C. npm run angular
D. ng go
Answer: A
23. What is a pure pipe?
A. A pipe with caching
B. A pipe without side effects and returns same output for same input
C. A pipe that mutates data
D. Not available in Angular
Answer: B
24. How to mark a service class for dependency injection?
A. Using @Component()
B. Using @Injectable()
C. Using @Service()
D. Using @Module()
Answer: B
25. What does FormControl represent?
A. A group of form fields
B. A single input field
C. A full form
D. Validation rule
Answer: B
26. Which Angular form type provides reactive programming features?
A. Template Driven Form
B. Simple Form
C. Reactive Form
D. Basic Form
Answer: C
27. Which class helps to group controls in reactive forms?
A. FormField
B. FormController
C. FormGroup
D. ControlGroup
Answer: C
28. What is the correct way to apply custom validation in Angular?
A. Through HTML5
B. Using CustomValidator class
C. Writing a function and adding it to validators array
D. Angular does not support custom validation
Answer: C
29. What operator in RxJS is commonly used to transform emitted values?
A. catchError
B. tap
C. map
D. subscribe
Answer: C
30. What is the role of an Angular interceptor?
A. Handle routing
B. Modify HTTP requests/responses
C. Control template rendering
D. Intercept component creation
Answer: B
31. What does HttpClient in Angular help with?
A. Reading local files
B. Styling
C. Sending HTTP requests
D. Managing forms
Answer: C
32. What are Observables used for in Angular?
A. Managing styling
B. Managing routing
C. Managing asynchronous data streams
D. Creating forms
Answer: C
33. Which HTTP method is used to submit data to server?
A. GET
B. POST
C. PUT
D. FETCH
Answer: B
34. Which decorator is used for dependency injection?
A. @Inject()
B. @Input()
C. @HostListener()
D. @Directive()
Answer: A
35. What is a route guard used for?
A. Securing routes from unauthorized access
B. Bootstrapping the app
C. Styling routes
D. Observing changes
Answer: A
36. What is RouterOutlet used for?
A. Declaring routes
B. Placeholder for rendering matched route component
C. Styling router
D. Exporting modules
Answer: B
37. What does ngSwitch help with?
A. Switching components
B. Switching styles
C. Rendering one of many elements
D. Switching modules
Answer: C
38. What is the use of @ContentChild()?
A. Read values from the DOM
B. Access content projected into a component
C. Intercept form submissions
D. Guard routes
Answer: B
39. What is an impure pipe?
A. It produces error
B. It returns cached results
C. It executes for every change detection cycle
D. Not allowed in Angular
Answer: C
40. Which object can be used to inspect an Angular app in browser console
(Angular >=9)?
A. window
B. ng
C. angularApp
D. rootApp
Answer: B
Absolutely! Here are more Angular multiple-choice questions along with
options and correct answers after each question:
32. Which of the following is NOT a valid HTTP method in Angular's HttpClient?
A. get
B. post
C. fetch
D. delete
Answer: C
33. Which directive is used to bind a form control in a template-driven form?
A. [(ngValue)]
B. formControl
C. ngModel
D. formGroup
Answer: C
34. What does Angular use to support dependency injection?
A. Services
B. Providers
C. Injector tree
D. All of the above
Answer: D
35. What does ngOnDestroy() lifecycle hook do?
A. Initializes the component
B. Cleans up just before the component is destroyed
C. Runs after the view is initialized
D. Triggers form submission
Answer: B
36. What file typically lists all dependencies of an Angular project?
A. angular.json
B. package.json
C. tsconfig.json
D. main.ts
Answer: B
37. What is the purpose of ng-template in Angular?
A. Add a new page
B. Define HTML that is not rendered by default
C. Replace component's metadata
D. Execute JavaScript
Answer: B
38. Which Angular concept separates business logic from UI logic?
A. Modules
B. Services
C. Directives
D. Pipes
Answer: B
39. What Angular feature is used to perform asynchronous operations like HTTP
calls?
A. Observables
B. Promises
C. Callbacks
D. All of the above
Answer: A
40. What is the default port for ng serve?
A. 4200
B. 8080
C. 8000
D. 3000
Answer: A
41. Which part of Angular is responsible for navigation between views?
A. HttpClient
B. RouterModule
C. FormsModule
D. ViewChild
Answer: B
42. Which keyword is used to define a route in Angular routing?
A. path
B. route
C. uri
D. url
Answer: A
43. What is the output of interpolation {{ 5 + 5 }} in Angular?
A. 10
B. "10"
C. {{10}}
D. Nothing
Answer: A
44. What happens if you forget to register a component in NgModule?
A. Nothing
B. Component is auto-registered
C. App throws an error
D. It works but without styling
Answer: C
45. Which Angular file is the entry point of the application?
A. index.html
B. app.module.ts
C. app.component.ts
D. main.ts
Answer: D
46. How can you create a service in Angular using CLI?
A. ng create service service-name
B. ng g s service-name
C. ng generate component service-name
D. ng build service
Answer: B
47. Which of the following is NOT a built-in Angular pipe?
A. date
B. currency
C. async
D. filter
Answer: D
48. What is the use of providedIn: 'root' in a service?
A. Limits the scope to the current module
B. Makes service available globally
C. Prevents service from being reused
D. None of the above
Answer: B
49. How do you handle errors in an Observable pipeline?
A. withRetry()
B. tap()
C. catchError()
D. map()
Answer: C
50. Which command is used to build an Angular project for production?
A. ng serve --prod
B. ng compile --production
C. ng build --prod
D. ng deploy
Answer: C