0% found this document useful (0 votes)
85 views54 pages

Angular SA Solution

The document consists of multiple-choice questions (MCQs) related to Angular concepts, including form control states, routing, TypeScript class instantiation, and iteration through arrays using *ngFor. Each question is followed by a correct answer, detailed explanations, and analyses of incorrect options. Key concepts and syntax rules are highlighted to aid understanding of Angular's functionality.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
85 views54 pages

Angular SA Solution

The document consists of multiple-choice questions (MCQs) related to Angular concepts, including form control states, routing, TypeScript class instantiation, and iteration through arrays using *ngFor. Each question is followed by a correct answer, detailed explanations, and analyses of incorrect options. Key concepts and syntax rules are highlighted to aid understanding of Angular's functionality.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

Question 1

Select the correct form control class name which is set to true in Angular 9
whenever value is modified.

a) ng-invalid
b) ng-pending
c) ng-pristine
d) ng-dirty

Correct Answer:
D) ng-dirty

Detailed Explanation:

• In Angular Forms, every form control automatically tracks its own state.
• When the user modifies the value of a form control (like typing something in an
input box), Angular marks that control as "dirty".
• When this happens, Angular applies the CSS class ng-dirty to the input element.
• "Dirty" here means "value has been changed" from its original state.

So, whenever you edit or type into a field ng-dirty becomes true!

Other Options Analysis:

• A) ng-invalid → Wrong!
➔ This is applied when validation fails, not when value is modified.
• B) ng-pending → Wrong!
➔ This shows up when the control is waiting for async validation (like checking
username availability), not just after editing.
• C) ng-pristine → Wrong!
➔ Pristine means "untouched", no user modification yet.
➔ As soon as you modify the value, pristine becomes false and dirty becomes true.

Related Concepts (Must Know!):

Class Name When It Applies


ng-pristine No user interaction yet
ng-dirty User has modified the value
ng-valid Validation rules are satisfied
ng-invalid Validation rules failed
ng-pending Async validation is happening

• pristine → dirty transition happens when user changes the field.


• valid ↔ invalid transition happens depending on whether the value satisfies
validations.

Key Things to Remember:

• ng-dirty = Modified field


• ng-pristine = Untouched field
• ng-valid = Correct value
• ng-invalid = Validation error
• ng-pending = Waiting for async check

Pro Tip:
Whenever user types, clicks, or edits the field ➔ Think "dirty" = ng-dirty!
(Just like dirty hands after writing — value is no longer clean/pristine!)

Question 2
Which component will be invoked for path "/search"?
Consider the below code:

const routes: Routes = [


{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'find', redirectTo: 'search' },
{ path: 'home', component: HomeComponent },
{ path: 'search', component: SearchComponent },
{ path: 'about', component: AboutComponent }
];

Hint:

• redirectTo: A URL to redirect to when the path matches


• pathMatch: Tells the router how it should match the URL provided in
order to redirect to the specified route
a) HomeComponent
b) SearchComponent
c) AboutComponent
d) FindComponent

Correct Answer:
B) SearchComponent

Detailed Explanation:
Let's walk through the route configuration carefully:

const routes: Routes = [


{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'find', redirectTo: 'search' },
{ path: 'home', component: HomeComponent },
{ path: 'search', component: SearchComponent },
{ path: 'about', component: AboutComponent }
];

➔ When you directly navigate to /search,


The router looks for an exact match (path: 'search')
It finds:

{ path: 'search', component: SearchComponent }

Thus, Angular loads the SearchComponent immediately!

Other Options Analysis:

• A) HomeComponent → Wrong!
➔ HomeComponent is loaded only when navigating to /home or when accessing the
root / (because of { path: '', redirectTo: 'home' }).
• C) AboutComponent → Wrong!
➔ AboutComponent would be loaded only for /about path.
• D) FindComponent → Wrong!
➔ Notice, there is no FindComponent at all!
➔ The path find is redirected to search, and we display the SearchComponent
instead.

Related Concepts (Must Know!):


Term Meaning
redirectTo Redirects from one URL to another
pathMatch: 'full' Entire URL must match exactly
component Component that is loaded for a path

redirectTo is only for changing the URL, not rendering a component directly.

If no pathMatch is specified, default is 'prefix', but for empty path ('') matching, we
should use pathMatch: 'full'.

Key Things to Remember:

• redirectTo ➔ Only redirects the URL, does NOT render a component itself .
• pathMatch: 'full' ➔ Important for root path ('') redirects!
• For exact URL like /search ➔ Direct match → corresponding component is invoked
.
• There’s no component called FindComponent here, just a redirect!

Pro Tip:
When you see redirectTo, follow the path!
Think like a detective :

• Where is it pointing?
• What does that new path load?

Final Thought:
Navigating to /search → loads SearchComponent

Question 3
Consider the below TypeScript code:

class Car {
public id: number = 10;
public name: string;

constructor();
constructor(name: string);
constructor(car: Car);
constructor(car?: any) {
if (typeof (car) == "string") {
this.name = car;
} else {
this.id = car.id;
this.name = car.name;
}
}
}

What are the valid ways to create an object for the Car class?

a) var car1 = new Car();


b) var car2 = new Car(1);
c) var car3 = new Car("Audi");
d) var car4 = new Car({ name: "Audi", id: 10 });

MCQ:
Given the TypeScript class Car, what are the valid ways to create an object?

Options:
A) var car1 = new Car();
B) var car2 = new Car(1);
C) var car3 = new Car("Audi");
D) var car4 = new Car({ name: "Audi", id: 10 });

Correct Answer:
A) car1, C) car3, D) car4
So correct choices are A, C, and D

Detailed Explanation:

Let's understand what the constructor is doing:

constructor();
constructor(name: string);
constructor(car: Car);
constructor(car?: any) {
if (typeof (car) == "string") {
this.name = car; // If string is passed ➔ assign to name
} else {
this.id = car.id; // If object is passed ➔ copy id
this.name = car.name; // copy name
}
}

• The constructor accepts:


o Nothing (i.e., new Car() )
o A string (i.e., new Car("Audi") )
o An object with id and name properties (i.e., new Car({ id: 10, name:
"Audi" }) )

If anything else is passed (like a number), it will crash .

Other Options Analysis:

• A) new Car(); → Valid!


➔ No arguments ➔ Default constructor is called.
➔ id is initialized to 10, name stays undefined.
• B) new Car(1); → Invalid!
➔ Number passed ➔ Neither a string nor an object!
➔ car.id will cause runtime error because primitive numbers don't have
properties like .id.
➔ Will throw "Cannot read properties of undefined" or similar.
• C) new Car("Audi"); → Valid!
➔ String passed ➔ assigns name = "Audi".
• D) new Car({ name: "Audi", id: 10 }); → Valid!
➔ Object passed ➔ assigns this.id = 10, this.name = "Audi".

Related Concepts (Must Know!):

Concept Meaning
Constructor TypeScript allows multiple constructor signatures but only one
Overloading actual implementation
typeof operator Used at runtime to check types like "string", "number",
"object"
car?: any The parameter is optional (?) and can be of any type (any)
Object checking In TypeScript/JS, objects have properties (numbers don't!)

TypeScript Rule:

• Overloads declare possible inputs, but


• Only one real constructor function exists to handle all cases internally.

Key Things to Remember:

• new Car(); ➔ No parameter ➔ OK


• new Car("Audi"); ➔ String ➔ OK
• new Car({id:10, name:"Audi"}); ➔ Object ➔ OK
• new Car(1); ➔ Number ➔ Invalid (error at runtime!)
• In TypeScript:
➔ Multiple constructor signatures allowed.
➔ Only one actual implementation block!

Pro Tip:
In exams, always check the data type passed in constructors for overloaded signatures!
If a number is passed where an object/string is expected, it usually causes error!

Final Thought:

• Correct creation ways: A) , C) , D)


• Wrong way: B) (Passing number causes issue!)

Question 4
Which of the below statements will iterate through the employees array?

a)

<tr *ngFor='let employee of employees'>


<td>{{employee.code}}</td>
<td>{{employee.name}}</td>
<td>{{employee.gender}}</td>
<td>{{employee.annualSalary}}</td>
<td>{{employee.dateOfBirth}}</td>
</tr>

b)

<tr *ngFor='for employee in employees'>


<td>{{employee.code}}</td>
<td>{{employee.name}}</td>
<td>{{employee.gender}}</td>
<td>{{employee.annualSalary}}</td>
<td>{{employee.dateOfBirth}}</td>
</tr>

c)

<tr *ngmodel='for employee in employees'>


<td>{{employee[i].code}}</td>
<td>{{employee[i].name}}</td>
<td>{{employee[i].gender}}</td>
<td>{{employee[i].annualSalary}}</td>
<td>{{employee[i].dateOfBirth}}</td>
</tr>

d)

<tr *ngIf='let employee of employees'>


<td>{{employee.code}}</td>
<td>{{employee.name}}</td>
<td>{{employee.gender}}</td>
<td>{{employee.annualSalary}}</td>
<td>{{employee.dateOfBirth}}</td>
</tr>

MCQ:
Which of the following statements will correctly iterate through the employees array in
Angular?

Options:
A)

<tr *ngFor='let employee of employees'>

B)

<tr *ngFor='for employee in employees'>

C)

<tr *ngmodel='for employee in employees'>

D)

<tr *ngIf='let employee of employees'>

Correct Answer:
A) <tr *ngFor='let employee of employees'>

Detailed Explanation:

• In Angular templates, to loop through an array (like employees), we use *ngFor


directive.
• The correct syntax for *ngFor is:
• *ngFor="let item of collection"
• Here:
o let employee ➔ defines a local variable for each item.
o of employees ➔ tells Angular to iterate over the employees array.
• So, Option A perfectly matches the Angular standard and will work correctly .

Other Options Analysis:

• B) *ngFor='for employee in employees' → Wrong!


o for is not a valid keyword inside *ngFor.
o Angular expects let ... of ... format, NOT for ... in ....
o Looks like a JavaScript style for-in loop, but in Angular templates, wrong
syntax!
• C) *ngmodel='for employee in employees' → Wrong!
o ngModel is for two-way data binding (for input fields etc.), NOT for
looping/iteration.
o Plus wrong attribute (*ngmodel instead of *ngFor) and wrong looping style.
• D) *ngIf='let employee of employees' → Wrong!
o *ngIf is used to conditionally display something based on a boolean
expression (like showing/hiding based on true/false), not for iteration.
o Using let employee of employees inside *ngIf doesn't make sense and
will cause an Angular error!

Related Concepts (Must Know!):

Directive Purpose Syntax


*ngFor To loop over arrays and collections *ngFor="let item of items"
*ngIf To conditionally include/exclude elements *ngIf="condition"
ngModel For two-way data binding in forms [()]="propertyName"

Remember:

• *ngFor ➔ iteration
• *ngIf ➔ show/hide based on condition
• ngModel ➔ binding form inputs

Key Things to Remember:

• Always use let variable of array format with *ngFor.


• *ngIf is NOT for loops .
• ngModel is NOT for iteration .
• Angular structural directives (like *ngFor, *ngIf) manipulate DOM based on
conditions.
Pro Tip:
In exams, if you see 'for' inside an Angular directive — immediately suspect it’s wrong!
Angular always uses let item of items, never for item in items!

Final Thought:

• Correct iteration: Option A.


• Other options ➔ syntax errors / wrong directive usage .

Question 5
Which of the below statements will iterate through the employees array?

a)

<tr *ngFor='let employee of employees'>


<td>{{employee.code}}</td>
<td>{{employee.name}}</td>
<td>{{employee.gender}}</td>
<td>{{employee.annualSalary}}</td>
<td>{{employee.dateOfBirth}}</td>
</tr>

b)

<tr *ngFor='for employee in employees'>


<td>{{employee.code}}</td>
<td>{{employee.name}}</td>
<td>{{employee.gender}}</td>
<td>{{employee.annualSalary}}</td>
<td>{{employee.dateOfBirth}}</td>
</tr>

c)

<tr *ngmodel='for employee in employees'>


<td>{{employee[i].code}}</td>
<td>{{employee[i].name}}</td>
<td>{{employee[i].gender}}</td>
<td>{{employee[i].annualSalary}}</td>
<td>{{employee[i].dateOfBirth}}</td>
</tr>

d)
<tr *ngIf='let employee of employees'>
<td>{{employee.code}}</td>
<td>{{employee.name}}</td>
<td>{{employee.gender}}</td>
<td>{{employee.annualSalary}}</td>
<td>{{employee.dateOfBirth}}</td>
</tr>

MCQ (Q5):
Which of the following statements will correctly iterate through the employees array?

Options:
A)

<tr *ngFor='let employee of employees'>


...
</tr>

B)

<tr *ngFor='for employee in employees'>


...
</tr>

C)

<tr *ngmodel='for employee in employees'>


...
</tr>

D)

<tr *ngIf='let employee of employees'>


...
</tr>

Correct Answer:
A) <tr *ngFor='let employee of employees'>

Detailed Explanation:

• *ngFor is the Angular structural directive used for looping over arrays.
• The only correct syntax is:
• *ngFor="let item of collection"
• Here:
o let employee creates a local variable for each iteration.
o of employees specifies the collection (array) to loop through.
• Therefore, in Option A, you properly loop over each employee in employees!
Other Options Analysis:

• B) *ngFor='for employee in employees' → Wrong!


➔ for employee in employees is JavaScript-style, not Angular syntax.
➔ Angular needs let ... of ..., not for ... in ....
• C) *ngmodel='for employee in employees' → Wrong!
➔ ngModel is for two-way binding with input fields, not for looping.
• D) *ngIf='let employee of employees' → Wrong!
➔ *ngIf is for conditional rendering, not looping!
➔ let ... of ... doesn't make sense with *ngIf.

Related Concepts (Must Know!):

Directive Used for


*ngFor Iterating over arrays/collections
*ngIf Showing/hiding elements based on condition
ngModel Binding form inputs for two-way data binding

Key Angular Syntax:

*ngFor="let item of items"

Key Things to Remember:

• *ngFor="let item of array" ➔ Correct way to loop.


• *ngIf ➔ Only for conditions — not loops!
• ngModel ➔ Only for input fields — not loops!

Pro Tip:
Whenever you see for used in an Angular template ➔ ALARM bells!
➔ Angular never uses for — only let ... of ...!

Quick Memory Trick:


Think: "LET'S iterate OF the array"

• LET ➔ let item


• OF ➔ of array
Simple and you’ll never forget it!
Final Thought:

• Correct looping: Option A


• Other options are incorrect

Question 5
Tina wants to invoke an API service that will return the price of a given book. The
signature of the API method is as shown below:

[HttpGet]
public float GetPrice(Int bookId);

The URL to invoke the GetPrice() method is stored in a variable


serviceUrl. Help her to identify the correct way to pass the parameter
and to invoke the API method from her Angular application.

Assume she wants to pass bookId as 3526.

Which among the following is a valid GET request?

a)

this.http.get<float>(serviceUrl).body({bookId=3526});

b)

bookId = 3526; this.http.get<float>(serviceUrl, bookId);

c)

bookObj = { bookId: 3526 }; this.http.get<float>(serviceUrl +


bookObj.toString());

d)

this.http.get<float>(serviceUrl + '?bookId=3526');

Alright!
This one is a super important MCQ because it checks your understanding of HTTP GET
requests in Angular and API parameter passing — something that's directly used in real-
world Angular projects!

Let’s break it down in the full engaging + exam-focused style!


MCQ (Q5):
Tina needs to make a GET request to the API method GetPrice(Int bookId).
How should she pass the bookId (3526) correctly?

Options:
A)

this.http.get<float>(serviceUrl).body({bookId=3526});

B)

bookId = 3526; this.http.get<float>(serviceUrl, bookId);

C)

bookObj = { bookId: 3526 }; this.http.get<float>(serviceUrl +


bookObj.toString());

D)

this.http.get<float>(serviceUrl + '?bookId=3526');

Correct Answer:
D) this.http.get<float>(serviceUrl + '?bookId=3526');

Detailed Explanation:

• In HTTP GET requests, parameters are passed through the URL query string .
• Syntax for a query string:
➔ ?key=value (first parameter)
➔ &key2=value2 (for additional parameters)
• So, if serviceUrl is like http://example.com/api/GetPrice,
then to pass bookId=3526,
final URL becomes:
http://example.com/api/GetPrice?bookId=3526
• In Angular's HttpClient, you simply append parameters to the URL for GET
requests like shown in Option D .

Thus, Option D is correct!

Other Options Analysis:


• A) this.http.get<float>(serviceUrl).body({bookId=3526}); → Wrong!
o get() does NOT have a .body() method.
o .body() is used internally inside HTTP Response, not while making a GET
request.
o Syntax error
• B) bookId = 3526; this.http.get<float>(serviceUrl, bookId); →
Wrong!
o Second parameter to http.get() must be options object, not a plain value
like 3526.
o Incorrect usage
• C) bookObj = { bookId: 3526 }; this.http.get<float>(serviceUrl +
bookObj.toString()); → Wrong!
o bookObj.toString() just returns [object Object], not a query string.
o URL would become something weird like:
http://example.com/api/GetPrice[object Object]
o Totally invalid URL!

Related Concepts (Must Know!):

Topic Key Point


HTTP GET in Angular Send data using query parameters
GET Syntax http.get<type>(url)
Query Parameters First param: ?key=value, next params: &key2=value2
POST vs GET POST sends data in body, GET sends data in URL

Quick formula for GET:

this.http.get<ReturnType>(url + '?param1=value1&param2=value2');

Key Things to Remember:

• In GET requests ➔ parameters go in URL, not body!


• .body() is not used while sending GET requests.
• Always use ?key=value format to append query parameters.

Pro Tip:
In real-world Angular projects , a better way is to use HttpParams instead of manually
appending query params:

let params = new HttpParams().set('bookId', '3526');


this.http.get<float>(serviceUrl, { params: params });

(But for MCQs — appending to URL is enough and matches your option D perfectly!)
Final Thought:

• Correct GET request to pass bookId=3526: Option D


• Other options are wrong because of syntax errors or wrong understanding.

Question 6
If you provide a custom service in two components’ providers section of the
@Component decorator, how many instances of the service shall get created?

a) 1
b) 2
c) 3
d) 4

MCQ (Q6):
If you provide a custom service in two components' providers array inside the
@Component decorator, how many instances of the service will be created?

Options:
A) 1
B) 2
C) 3
D) 4

Correct Answer:
B) 2

Detailed Explanation:

• In Angular, services are singleton by default, ONLY IF they are provided in root
(providedIn: 'root') or at module level.
• BUT... if you provide a service in the providers array of a @Component
decorator,
➔ a new instance of the service is created for that component and its children!
• So here:
o Component 1 provides the service → gets its own instance
o Component 2 provides the service → gets its own separate instance
• Thus, TWO SEPARATE instances are created — one for each component!

Simple Picture:

Component Service Instance


Component A Instance 1
Component B Instance 2

2 components ➔ 2 separate instances!

Other Options Analysis:

• A) 1 → Wrong!
➔ Would be correct only if service was provided in root or at module level, not at
component level.
• C) 3 → Wrong!
➔ Only 2 components are involved, so 3 instances make no sense!
• D) 4 → Wrong!
➔ Definitely not! No such rule in Angular.

Related Concepts (Must Know!):

Service Provided At Instances Created


providedIn: 'root' (in service) Single instance (application-wide singleton)
Module's providers array (NgModule) Single instance (module-wide singleton)
Component's providers array New instance for each component
(@Component) providing it

Component-level providing ➔ creates a new separate copy for that component!

Key Things to Remember:

• Component-level service providing = New instance per component.


• Module or Root level providing = Single shared instance across components.
• Angular dependency injection is hierarchical — components first look in their own
injector, then up the tree.
Pro Tip:
If you want to share data across multiple unrelated components ➔ provide service at root
(singleton).
If you want isolation (separate states per component) ➔ provide at component level!

Final Thought:

• Two components providing the same service ➔ Two instances created.


• Correct answer = B) 2

Question 7
Which of the below codes will give the output in this format – "5:13 PM"?
Note: dateVal is an instance of new Date().

a)

<div class="card card-block">


<h4 class="card-title">Date</h4>
<div class="card-text">
<p>{{ dateVal | date: 'fullTime' }}</p>
</div>
</div>

b)

<div class="card card-block">


<h4 class="card-title">Date</h4>
<div class="card-text">
<p>{{ dateVal | date: 'time' }}</p>
</div>
</div>

c)

<div class="card card-block">


<h4 class="card-title">Date</h4>
<div class="card-text">
<p>{{ dateVal | date: 'shortTime' }}</p>
</div>
</div>

d)
<div class="card card-block">
<h4 class="card-title">Date</h4>
<div class="card-text">
<p>{{ dateVal | date: 'Time' }}</p>
</div>
</div>

MCQ (Q7):
Which code will format dateVal to output like "5:13 PM"?

(Note: dateVal is an instance of new Date().)

Options:
A) dateVal | date: 'fullTime'
B) dateVal | date: 'time'
C) dateVal | date: 'shortTime'
D) dateVal | date: 'Time'

Correct Answer:
C) dateVal | date: 'shortTime'

Detailed Explanation:

• In Angular, date pipe (| date) is used to format dates in templates.


• You can pass different format strings to tell Angular how to display the date/time.

Here’s the difference:

Format Example Output Description


fullTime 5:13:45 PM GMT+5:30 Includes seconds and timezone
time Invalid format (no such standard
format)
shortTime 5:13 PM Only hours and minutes,
AM/PM
Time Invalid (case sensitive, "Time" not
recognized)

So, if you want something like "5:13 PM", you must use 'shortTime'!

Other Options Analysis:


• A) 'fullTime' →
➔ Gives hours:minutes:seconds timezone — e.g., 5:13:45 PM GMT+5:30
➔ Too much detail! Not just "5:13 PM".
• B) 'time' →
➔ Wrong format string.
➔ date pipe does not recognize 'time' as a valid format. (will give an error or
fallback to default)
• D) 'Time' →
➔ Angular pipes are case-sensitive!
➔ 'Time' with capital "T" is invalid .

Related Concepts (Must Know!):

Angular DatePipe Format Meaning


shortTime HH:mm a (hours:minutes AM/PM)
mediumTime HH:mm:ss a
longTime HH:mm:ss a z (includes timezone abbreviation)
fullTime HH:mm:ss zzzz (full timezone info)

Always remember: shortTime = only hours and minutes with AM/PM.

Key Things to Remember:

• Pipes are case-sensitive in Angular!


• 'shortTime' ➔ gives only hours and minutes ➔ "5:13 PM" format
• 'fullTime' ➔ gives hours:minutes:seconds + timezone too detailed for this
question.
• Wrong formats ('time', 'Time') ➔ error or fallback .

Pro Tip:
If you ever forget, just think:
"shortTime = short output = only hours & minutes"
Simple memory trick!

Final Thought:

• Correct formatting: C) shortTime


• Others either give wrong output or error.
Question 8
What will be the output when the below code written in Test.component.html
file is executed?

Assume showMsgDiv has value as False.

<div *ngIf="showMsgDiv; else elseBlock">


<p>
True block
</p>
</div>

<ng-template #elseBlock>
<p>False block</p>
</ng-template>

a) True block False block


b) True block
c) False block
d) Error stating elseBlock is not a known element of div tag

MCQ (Q8):
What will be the output when the following is executed?

Given:

• showMsgDiv = false

<div *ngIf="showMsgDiv; else elseBlock">


<p>True block</p>
</div>

<ng-template #elseBlock>
<p>False block</p>
</ng-template>

Options:
A) True block False block
B) True block
C) False block
D) Error stating elseBlock is not a known element of div tag

Correct Answer:
C) False block
Detailed Explanation:

• *ngIf="condition; else elseTemplate"


➔ This syntax means:
o If condition is true → Show the div content (True block).
o If condition is false → Display the content inside the elseTemplate.
• Here:
o showMsgDiv = false
o So, the <div> is NOT rendered at all
o Instead, Angular jumps to the <ng-template #elseBlock>
o Displays:
o <p>False block</p>

Thus, the output will be only "False block"

Other Options Analysis:

• A) True block False block → Wrong!


➔ Both cannot be printed!
➔ Only one branch is executed: true or false, not both.
• B) True block → Wrong!
➔ True block only shown if showMsgDiv = true, but here it's false.
• D) Error stating elseBlock is not a known element → Wrong!
➔ <ng-template> is a valid Angular built-in tag.
➔ No error occurs.

Related Concepts (Must Know!):

Directive/Concept Meaning
*ngIf="condition" Shows element only if condition is true
else block Alternate block to render if condition is false
<ng-template> Defines a template that is not rendered unless explicitly called

ng-template is special — it’s like an invisible container which Angular only renders
when asked!

Key Things to Remember:

• *ngIf="condition; else elseBlock" ➔ If condition false, jump to elseBlock.


• <ng-template> is valid Angular element, not an error.
• Only one block is rendered based on condition — not both.
Pro Tip:
Remember the flow like a quick story :
If condition is true, live normally ➔ show main content.
If condition is false, go to plan B (elseBlock) ➔ show alternative.

Final Thought:

• Output: False block


• Correct option: C

Question 9
Consider the following code snippet:

export class DemoComponent implements OnInit {


emp1 = new Employee();
emp2: Employee;
emp3 = this.emp1;

constructor() { }

empList = [this.emp1, this.emp2, this.emp3];

ngOnInit() { }
}

What will happen when the below code is executed?

<div *ngIf="emp1">
Inside first div element
</div>

<div *ngIf="emp2">
Inside second div element
</div>

<div *ngIf="emp3">
Inside third div element
</div>
a) Inside first div element
Inside second div element
Inside third div element

b) Inside first div element


Inside second div element

c) Inside first div element


Inside third div element

d) Compilation error

MCQ (Q9):
Given the Angular component and template code, what will be the output?

export class DemoComponent implements OnInit {


emp1 = new Employee(); // New object created
emp2: Employee; // Only declared, NOT initialized
emp3 = this.emp1; // Points to same object as emp1

constructor() { }

empList = [this.emp1, this.emp2, this.emp3];

ngOnInit() { }
}

HTML:

<div *ngIf="emp1">
Inside first div element
</div>

<div *ngIf="emp2">
Inside second div element
</div>

<div *ngIf="emp3">
Inside third div element
</div>

Options:
A) Inside first div element
Inside second div element
Inside third div element

B) Inside first div element


Inside second div element

C) Inside first div element


Inside third div element
D) Compilation error

Correct Answer:
C) Inside first div element
Inside third div element

Detailed Explanation:

• emp1 = new Employee();


➔ New object created
➔ Non-null / Truthy ➔ <div *ngIf="emp1"> will render!
• emp2: Employee;
➔ Only declared but not assigned!
➔ Default value in TypeScript = undefined
➔ Falsy ➔ <div *ngIf="emp2"> will NOT render!
• emp3 = this.emp1;
➔ Assigned to same object as emp1
➔ Truthy ➔ <div *ngIf="emp3"> will render!

Summary:

Div Block Will Render? Reason


First div (emp1) Yes emp1 is initialized
Second div (emp2) No emp2 is undefined
Third div (emp3) Yes emp3 points to emp1

Other Options Analysis:

• A)
➔ Wrong!
➔ All three won't render because emp2 is undefined.
• B)
➔ Wrong!
➔ emp2 still won't render, but missing third div here.
• D)
➔ Wrong!
➔ No compilation error.
➔ undefined is allowed at runtime for objects — Angular simply hides the div if
condition is falsy.
Related Concepts (Must Know!):

Concept Key Point


*ngIf directive Shows element only if the condition is truthy
Truthy values Any non-null, non-undefined, non-false, non-0 value
Undefined in TypeScript Default value if a variable is declared but not initialized

In templates, undefined variables just don't render the block quietly — no crash or
error!

Key Things to Remember:

• new Employee() ➔ Truthy object


• Undefined variable ➔ Falsy
• *ngIf only renders elements if the value is truthy.

Pro Tip:
In Angular templates, when using *ngIf, always initialize your objects or you might get
surprising empty screens!

Final Thought:

• Output = "Inside first div element" and "Inside third div element"
• Correct option: C

Question 10
State True or False.

<router-outlet></router-outlet> is one of the router directives


provided by RouterModule, which specifies where the views have to be
rendered.

a) True
b) False
MCQ (Q10):
State True or False:
<router-outlet></router-outlet> is one of the router directives provided by
RouterModule, which specifies where the views have to be rendered.

Options:
A) True
B) False

Correct Answer:
A) True

Detailed Explanation:

• In Angular, when you use routing, you define different components to load based
on the URL.
• <router-outlet> is a special Angular directive provided by the RouterModule.

• It acts like a placeholder (container) where the router dynamically loads the
component based on the current route.
• Without <router-outlet>, the router wouldn't know where to display the routed
component on the page!

So YES,
<router-outlet> is absolutely provided by RouterModule.
It tells Angular where to inject/render the routed views.

Related Concepts (Must Know!):

Concept Key Point


<router-outlet> Acts as a placeholder for loading routed components
RouterModule Must be imported to use Angular routing features
<router-outlet> Determines where on the page the routed component will
location appear

You can have multiple <router-outlet> in the same page for advanced routing (like
nested routes)!

Key Things to Remember:


• <router-outlet> is a built-in directive, NOT a custom HTML tag.
• It is mandatory in routed Angular apps — without it, no component will display on
route change!
• It works along with <a [routerLink]="['/path']"> to navigate.

Pro Tip:
Think of <router-outlet> like a theater stage :

• Different plays (components) perform on the same stage (outlet) depending on the
audience (URL).

Final Thought:

• Statement is TRUE
• Correct answer = A) True

Question 11
Consider the below component model:

email: string;
phone: number;

onSubmit() {
console.log(this.email, this.phone);
}

What should be the code in the view so that it creates a form as shown below?
The data entered by the user should be displayed on the console when the form
is submitted.

a)

<form (ngSubmit)="onSubmit()">
Email:<input type="email" [(ngModel)]="email" name="txtEmail">
<br>
Phone:<input type="number" required [(ngModel)]="phone"
name="txtPhone">
<br>
<button type="submit">Submit</button>
</form>

b)
<form #frm="ngForm" (ngSubmit)="onSubmit()">
Email:<input type="email" [(ngModel)]="email" name="txtEmail"
#em="ngModel">
<br>
Phone:<input type="number" required [(ngModel)]="phone"
name="txtPhone" #ph="ngModel">
<br>
<button type="submit">Submit</button>
</form>

c)

<form>
Email:<input type="email" [(ngModel)]="email">
<br>
Phone:<input type="number" required [(ngModel)]="phone">
<br>
<button type="submit" (submit)="onSubmit()">Submit</button>
</form>

d)

<form>
Email:<input type="email" [(ngModel)]="email">
<br>
Phone:<input type="number" required [(ngModel)]="phone">
<br>
<button type="submit" (submit)="onSubmit()">Submit</button>
</form>

What is the correct option?

a) Only A
b) Only B
c) A and B
d) A, B and C

MCQ (Updated Q11):


Given the component model:

email: string;
phone: number;

onSubmit() {
console.log(this.email, this.phone);
}

Which code will correctly create a form that:

• Binds inputs to component properties


• Displays user-entered data in console on submit
Correct Answer:
C) A and B

Detailed Explanation:

Option A Analysis:

<form (ngSubmit)="onSubmit()">
Email:<input type="email" [(ngModel)]="email" name="txtEmail">
<br>
Phone:<input type="number" required [(ngModel)]="phone" name="txtPhone">
<br>
<button type="submit">Submit</button>
</form>

• [(ngModel)]="email" and [(ngModel)]="phone" ➔ Two-way binding


• name="txtEmail" and name="txtPhone" ➔ Name attributes present
• (ngSubmit)="onSubmit()" attached to <form> ➔ Correct
• No errors. Data will print in console!

Option B Analysis:

<form #frm="ngForm" (ngSubmit)="onSubmit()">


Email:<input type="email" [(ngModel)]="email" name="txtEmail"
#em="ngModel">
<br>
Phone:<input type="number" required [(ngModel)]="phone" name="txtPhone"
#ph="ngModel">
<br>
<button type="submit">Submit</button>
</form>

• Same good setup as Option A, but with extras:


o #frm="ngForm" ➔ assigns form to a template reference variable (useful for
validation, but optional here).
o #em="ngModel" and #ph="ngModel" ➔ assigns input controls to template
variables (again optional, not harming anything).
• Data binding and submit action are still perfectly correct

Thus, both A and B are correct!

Other Options Analysis:

• Option C Analysis:
<form>
Email:<input type="email" [(ngModel)]="email">
<br>
Phone:<input type="number" required [(ngModel)]="phone">
<br>
<button type="submit" (submit)="onSubmit()">Submit</button>
</form>

• Problem 1: Inputs are missing the name attribute — ngModel needs a name.
• Problem 2: (submit)="onSubmit()" wrongly placed on button instead of form!

• Will not work correctly!


• Option D is exactly same as C ➔ also wrong.

Related Concepts (Must Know!):

Concept Key Point


[(ngModel)] Two-way binds input with component variable
name attribute Mandatory for ngModel inside <form>
(ngSubmit) Should be on <form>, not <button>
Template references (#frm, #em) Optional, used for validations

You can safely add #frm and #em even if you are not doing validation.

Key Things to Remember:

• Always put (ngSubmit) on <form> NOT on <button>.


• When using [(ngModel)] in form ➔ must have a name.
• Template references (#something) are optional for simple forms.

Pro Tip:
In exams, quickly check: [(ngModel)] present?
name attribute there?
(ngSubmit) on <form>?
If yes, the form setup is correct!

Final Thought:

• Correct answer = C) A and B


Question 12
Analyze the given code snippet inside app.routing.ts file and find which
component will be displayed if the URL is http://localhost:4200/empty?

const routes: Routes = [


{ path: 'home', component: HomeComponent },
{ path: '', component: CheckComponent },
{ path: 'empty', redirectTo: '', pathMatch: 'full' },
{ path: '**', component: CommonComponent }
];

a) CheckComponent
b) CommonComponent
c) HomeComponent
d) Compilation error

MCQ (Q12):
Given the following routes configuration:

const routes: Routes = [


{ path: 'home', component: HomeComponent },
{ path: '', component: CheckComponent },
{ path: 'empty', redirectTo: '', pathMatch: 'full' },
{ path: '**', component: CommonComponent }
];

If the URL is http://localhost:4200/empty,


Which component will be displayed?

Options:
A) CheckComponent
B) CommonComponent
C) HomeComponent
D) Compilation error

Correct Answer:
A) CheckComponent

Detailed Explanation:
• User accesses /empty ➔
➔ The router checks if there’s a match.
• { path: 'empty', redirectTo: '', pathMatch: 'full' }
o Found! empty path redirects to '' (empty path).
o pathMatch: 'full' means it only matches if the full URL is /empty, which
it is.
• So Angular now navigates to '' (empty path).
• Next, { path: '', component: CheckComponent }
o Empty path ('') is mapped to CheckComponent
• Thus CheckComponent is displayed!

Quick Flow :
/empty
➔ Redirects to / (empty path)
➔ Empty path loads ➔ CheckComponent

Other Options Analysis:

• B) CommonComponent →
➔ ** (wildcard) is used only if no other routes match.
➔ Here, a route matches (empty ➔ redirect to ''), so wildcard is not triggered.
• C) HomeComponent →
➔ home path is only triggered if URL is /home, not /empty.
• D) Compilation error →
➔ No syntax or configuration error here.
➔ The routes are correctly defined.

Related Concepts (Must Know!):

Concept Key Point


redirectTo Redirects the URL to another path
pathMatch: 'full' Entire URL must match exactly
** (wildcard route) Matches any URL not caught by above routes
'' empty path Generally maps to default landing page component

Wildcard ** is a last resort — used only if no earlier routes match!

Key Things to Remember:


• redirectTo ➔ internally redirects the URL without showing the previous
component.
• pathMatch: 'full' ➔ critical when matching whole URL.
• ** ➔ wildcard match, only if none of the routes above it match.

Pro Tip:
When you see a redirectTo pointing to '',
it means "go home" (default route component)!

Final Thought:

• Correct component displayed: CheckComponent


• Correct answer: A) CheckComponent

Question 13
Observe the given code and choose the correct option:

getReviews(bookId: string): Observable<IRating[]> {


let tempVar =
this.http.get<IRating[]>(`https://localhost:44327/api/Rating/GetAllRev
iewsonBookId?bookId=` + bookId)
.pipe(catchError(this.errorHandler));
return tempVar;
}

a) The HttpClient get() method converts the synchronously received Observable


array of type IRating to JSON data.
b) The HttpClient get() method converts the synchronously received JSON data to
an Observable array of type IRating.
c) The HttpClient get() method converts the asynchronously received JSON data
to an Observable array of type IRating.
d) The HttpClient get() method converts the asynchronously received Observable
array of type IRating to JSON data.

MCQ (Q13):
Given the code:

getReviews(bookId: string): Observable<IRating[]> {


let tempVar =
this.http.get<IRating[]>(`https://localhost:44327/api/Rating/GetAllReviewso
nBookId?bookId=` + bookId)
.pipe(catchError(this.errorHandler));
return tempVar;
}

Question:
What actually happens when this getReviews() method is called?

Options:
A) The HttpClient get() method converts the synchronously received Observable array of
type IRating to JSON data.
B) The HttpClient get() method converts the synchronously received JSON data to an
Observable array of type IRating.
C) The HttpClient get() method converts the asynchronously received JSON data to an
Observable array of type IRating.
D) The HttpClient get() method converts the asynchronously received Observable array of
type IRating to JSON data.

Correct Answer:
C) The HttpClient get() method converts the asynchronously received JSON data to an
Observable array of type IRating.

Detailed Explanation:

• In Angular, HttpClient sends HTTP requests asynchronously (not blocking, it


waits for server response without freezing the app) .
• The server responds with JSON data.
• Angular automatically parses this JSON data into a TypeScript object/array —
based on the generic type provided (in this case, IRating[]).
• Then it wraps this parsed object inside an Observable.

Thus:

• JSON data is asynchronously received


• Then converted to an Observable<IRating[]>

Exactly what Option C says!

Why other options are wrong?

• A) "synchronously received Observable array" ➔ Wrong!


➔ HTTP calls are asynchronous, not synchronous.
• B) "synchronously received JSON" ➔ Wrong!
➔ Again, HTTP communication is asynchronous.
• D) "Observable array to JSON" ➔ Wrong!
➔ It’s the opposite: server sends JSON, Angular converts it to Observable of
objects!

Related Concepts (Must Know!):

Concept Key Point


HttpClient Makes async HTTP requests
Response from API Typically JSON format
Generic Typing <IRating[]> Informs HttpClient about expected data type
Observable Wraps the asynchronous result for subscription

So get<IRating[]> ➔ means:
"Expect a list of IRating objects coming back from the server".

Key Things to Remember:

• HTTP calls in Angular are always asynchronous.


• Server sends JSON ➔ Angular maps it to your typed object.
• Observable allows you to subscribe and react once the data comes.

Pro Tip:
If you ever get confused, just think:
API ➔ sends JSON
Angular ➔ unwraps JSON, wraps in Observable
You ➔ subscribe to get your typed object!

Final Thought:

• Correct answer: C) The HttpClient get() method converts the asynchronously


received JSON data to an Observable array of type IRating.
Question 14
In Angular 9 routing, which of the below tags is used to render matched
component via active route?

a) <router></router>
b) <router-output></router-output>
c) <router-outlet></router-outlet>
d) <router-display></router-display>

Let's go!
This Question 14 is super important because it checks your basics on Angular Routing and
Component Rendering!

I’ll explain it fully in exam-focused + fun style

MCQ (Q14):
In Angular 9 routing, which tag is used to render the matched component based on the
active route?

Options:
A) <router></router>
B) <router-output></router-output>
C) <router-outlet></router-outlet>
D) <router-display></router-display>

Correct Answer:
C) <router-outlet></router-outlet>

Detailed Explanation:

• In Angular, when you navigate to a route (like /home, /about), the router needs a
placeholder to inject the matching component dynamically onto the page.
• That placeholder is ➔ <router-outlet>!
• <router-outlet> is a special Angular directive provided by RouterModule.
• Angular will look at the URL, find the matching route, and then render the correct
component inside <router-outlet>.

So, without <router-outlet>, Angular wouldn’t know where to place the routed
components!
Why Other Options Are Wrong:

• A) <router> → Wrong!
➔ Not an Angular element. No such thing as <router> tag.
• B) <router-output> → Wrong!
➔ Looks close, but wrong keyword. It's outlet, not output.
• D) <router-display> → Wrong!
➔ Sounds logical, but Angular doesn't have this tag either.

Related Concepts (Must Know!):

Concept Key Point


<router-outlet> Placeholder where routed components are displayed
RouterModule Must be imported to enable routing
Route Defines a URL path and the component to display
Dynamic Rendering Happens automatically when the active route changes

In fact, you can have multiple <router-outlet> for nested routes too!

Key Things to Remember:

• Single-page application (SPA) model ➔ Angular uses <router-outlet> to swap


views dynamically without full page reloads.
• <router-outlet> is mandatory when you're using RouterModule and routes.

Pro Tip:
Think of <router-outlet> like a theater stage —

• Different plays (components) perform on the same stage depending on the audience
request (URL route).

Final Thought:

• Correct tag: C) <router-outlet>


• Others are invalid and will cause Angular errors!
Question 15
Which of the following keywords is not a directive?

a) ngIf
b) ngFor
c) ngModel
d) ngOnInit

MCQ (Q15):
Which of the following keywords is NOT a directive?

Options:
A) ngIf
B) ngFor
C) ngModel
D) ngOnInit

Correct Answer:
D) ngOnInit

Detailed Explanation:

Let’s quickly check each one:

• A) ngIf →
➔ Structural directive ➔ Shows/hides elements based on a condition.
➔ Example:

<div *ngIf="showContent">Hello!</div>

• B) ngFor →
➔ Structural directive ➔ Used for looping over arrays/collections.
➔ Example:

<li *ngFor="let item of items">{{ item }}</li>

• C) ngModel →
➔ Attribute directive ➔ Enables two-way data binding between input elements
and component properties.
➔ Example:

<input [(ngModel)]="userName">
• D) ngOnInit →
➔ NOT a directive!
➔ It is a lifecycle hook interface in Angular. ➔ Used to write logic that should run
when a component is initialized.
➔ Example (in component class, NOT in HTML):

export class MyComponent implements OnInit {


ngOnInit() {
console.log('Component initialized!');
}
}

Simple way to remember:

• ngIf, ngFor, ngModel➔ template-level ➔ used inside HTML ➔ directives.


• ngOnInit ➔ class-level method ➔ used inside TypeScript classes ➔ lifecycle hook.

Related Concepts (Must Know!):

Keyword Type Purpose


ngIf Structural Directive Show/hide elements
ngFor Structural Directive Loop through collections
ngModel Attribute Directive Two-way data binding
ngOnInit Lifecycle Hook Logic to run after component initialization

Directives ➔ modify DOM structure or behavior.


Lifecycle Hooks ➔ handle different stages in a component's life.

Key Things to Remember:

• Directives affect HTML templates.


• Lifecycle hooks are written inside TypeScript classes.

Pro Tip:
If it starts with * or is used inside HTML ➔ it's almost certainly a directive!
If it's a method inside a component class ➔ it's a lifecycle hook!

Final Thought:
• Correct answer = D) ngOnInit
• ngIf, ngFor, ngModel are directives.

Question 16
Jill wants to display the price as "USD 2,021.00" in her Angular project.
Which of the following pipe should she choose?

a) {{ 2021 | currency : 'USD' : 'code' }}


b) {{ 2021 | currency : 'USD' : true }}
c) {{ 2021 | currency : 'USD' : 'String' }}
d) {{ 2021 | currency : 'USD' : 'Dollars' }}

MCQ (Q16):
Jill wants to display the price as "USD 2,021.00" in her Angular project.
Which pipe syntax should she choose?

Options:
A) {{ 2021 | currency : 'USD' : 'code' }}
B) {{ 2021 | currency : 'USD' : true }}
C) {{ 2021 | currency : 'USD' : 'String' }}
D) {{ 2021 | currency : 'USD' : 'Dollars' }}

Correct Answer:
A) {{ 2021 | currency : 'USD' : 'code' }}

Detailed Explanation:

• Angular's currency pipe is used to format numbers as currency.


• General syntax of currency pipe:
• {{ amount | currency : currencyCode : display : digitsInfo : locale
}}
• Parameters:
o currencyCode ➔ Like 'USD', 'INR', 'EUR'
o display
▪ 'symbol' ➔ shows $, ₹, € (default)
▪ 'code' ➔ shows USD, INR, EUR
▪ 'symbol-narrow' ➔ shows a compact version of symbol (if
available)
In Jill's case:

• She wants "USD 2,021.00" — notice USD (currency code) before the amount.
• Thus ➔ display = 'code'

Therefore:

{{ 2021 | currency : 'USD' : 'code' }}

will output: USD 2,021.00

Matches perfectly!

Other Options Analysis:

• B) true as display param →


➔ Wrong! Angular expects 'symbol', 'code', or 'symbol-narrow', NOT true.
• C) 'String' as display param →
➔ Wrong! 'String' is invalid. Only allowed: 'symbol', 'code', 'symbol-
narrow'.
• D) 'Dollars' as display param →
➔ Wrong! 'Dollars' is not a valid display option either.

Related Concepts (Must Know!):

Parameter Meaning
'symbol' Default, displays currency symbol ($, ₹, €)
'code' Displays 3-letter ISO code (USD, INR, EUR)
'symbol-narrow' Displays narrow version of the symbol (if available)
digitsInfo Optional format to control decimal places

You can also control number format like "1.0-2" (min 1 integer, min 0 fraction, max 2
fractions).

Key Things to Remember:

• Want $? ➔ use 'symbol'.


• Want USD? ➔ use 'code'.
• currency pipe formats asynchronously based on Angular i18n settings.
Pro Tip:
If you want the currency code like "USD 2,021.00", just remember "code = code!"
Simple memory hack!

Final Thought:

• Correct syntax for Jill = A) {{ 2021 | currency : 'USD' : 'code' }}


• Others are invalid display types.

Question 17
Robert has written the below code for routing. Predict the output by
considering all are valid components of the application.

{ path: '', component: GetTableDetailsComponent },


{ path: 'addTable', component: AddCustomerComponent },
{ path: 'addTable', component: AddCustodianComponent },

a) AddCustomerComponent will load when addTable is given in URL


b) AddCustodianComponent will load when addTable is given in URL
c) GetTableDetailsComponent will load by default
d) The code will throw error since we cannot give same routing name for more
than one component

MCQ (Q17):
Robert's routing code:

{ path: '', component: GetTableDetailsComponent },


{ path: 'addTable', component: AddCustomerComponent },
{ path: 'addTable', component: AddCustodianComponent }

What happens if you navigate to URL /addTable?

Options:
A) AddCustomerComponent will load when addTable is given in URL
B) AddCustodianComponent will load when addTable is given in URL
C) GetTableDetailsComponent will load by default
D) The code will throw error since we cannot give same routing name for more than one
component
Correct Answer:
B) AddCustodianComponent will load when addTable is given in URL

Detailed Explanation:

• In Angular routes configuration, if two routes have the same path, the last one
wins!
• Angular will override the earlier route with the later one silently — no compilation
error .
• It simply keeps the last matching route definition in memory at runtime.

What happens in Robert's code:

• First { path: 'addTable', component: AddCustomerComponent } is registered

• Then { path: 'addTable', component: AddCustodianComponent } overrides it


silently
• So now, navigating to /addTable ➔ loads AddCustodianComponent.

No error will occur during compilation. Angular picks the last defined component.

Quick Internal View :

Path Component What happens?


'' GetTableDetailsComponent Default route, loads for /
'addTable' (first one) AddCustomerComponent Ignored later
'addTable' (second one) AddCustodianComponent Final winner

So /addTable → AddCustodianComponent loaded!

Other Options Analysis:

• A) AddCustomerComponent will load →


➔ No, it gets overridden by the second route.
• C) GetTableDetailsComponent will load by default →
➔ Only when path is empty (/), not for /addTable.
• D) Compilation error will occur →
➔ Angular does not throw compile errors for duplicate paths, it silently overrides.
Related Concepts (Must Know!):

Concept Key Point


Route Matching Angular matches routes top-to-bottom
Duplicate Paths Last one overrides earlier ones
Default Route ('') Loads when path is empty
No Compile Error Even for duplicate paths

Always avoid duplicate paths ➔ it’s confusing and bad practice, but Angular won't stop
you!

Key Things to Remember:

• In Angular routing, the last route with same path overrides previous ones.
• No compilation error happens.
• Be careful when designing route paths to avoid confusion!

Pro Tip:
In real projects, use unique paths or child routes to organize components properly!
Duplicate paths silently overriding can cause major debugging nightmares .

Final Thought:

• Correct behavior: B) AddCustodianComponent will load when addTable is


given in URL
• No compilation error!

Question 18
Sam has created two component classes called FirstComponent and
SecondComponent and he wants to make them available to the entire
module. In which of the following properties of NgModule should he declare
these two classes?

a) imports: [FirstComponent, SecondComponent]


b) declarations: [FirstComponent, SecondComponent]
c) bootstrap: [FirstComponent, SecondComponent]
d) providers: [FirstComponent, SecondComponent]
MCQ (Q18):
Sam has created two component classes: FirstComponent and SecondComponent.
He wants to make them available throughout the module.
In which property of @NgModule should he declare them?

Options:
A) imports: [FirstComponent, SecondComponent]
B) declarations: [FirstComponent, SecondComponent]
C) bootstrap: [FirstComponent, SecondComponent]
D) providers: [FirstComponent, SecondComponent]

Correct Answer:
B) declarations: [FirstComponent, SecondComponent]

Detailed Explanation:

• In Angular, inside an @NgModule, the declarations array is used to declare


components, directives, and pipes that belong to that module.
• If you want a component (like FirstComponent, SecondComponent) to be usable in
the templates of the module, you must declare it inside the declarations property.

So the correct place to list Sam’s components is:

@NgModule({
declarations: [FirstComponent, SecondComponent],
...
})

Why Other Options Are Wrong:

• A) imports →
➔ Used to import other modules (not components, directives, or pipes).
➔ Example: BrowserModule, FormsModule, HttpClientModule, etc.
• C) bootstrap →
➔ Used to launch the main/root component (typically just one, like
AppComponent). ➔ Only the starting component goes here, not multiple normal
components.
• D) providers →
➔ Used to register services (singleton classes) for dependency injection, not
components.
Related Concepts (Must Know!):

NgModule Property Purpose


declarations Declare components, directives, and pipes for the module
imports Import other Angular modules
providers Provide services and injectables
bootstrap Launch the main root component of the app

Remember:

• Components ➔ go to declarations
• Modules ➔ go to imports
• Services ➔ go to providers
• Startup component ➔ goes to bootstrap

Key Things to Remember:

• Always declare your components, directives, and pipes inside declarations.


• You import modules like FormsModule, ReactiveFormsModule, not components!
• You provide services like HttpClient, not components!
• You bootstrap only the main/root component (typically once).

Pro Tip:
If it's something you use in HTML templates (components, pipes, directives) ➔ always
think declarations!

Final Thought:

• Correct answer: B) declarations: [FirstComponent, SecondComponent]


• Other options are for different purposes!

Question 19
If the array is:

boatArr = [
{ boatId: 1, boatName: 'Boat1', boatRating: 30 },
{ boatId: 2, boatName: 'Boat2', boatRating: 32 },
{ boatId: 3, boatName: 'Boat3', boatRating: 34 },
{ boatId: 4, boatName: 'Boat4', boatRating: 37 }
];

And the output is:

boatId boatRating boatName


1 30
2 32
3 34
4 Boat4 37

Which of the following will give correct output?

a)

<table>
<tr *ngFor="let boat of boatArr">
<td>{{boat.boatId}}</td>
<td *ngIf="boat.boatRating>35">{{boat.boatName}}</td>
<td>{{boat.boatRating}}</td>
</tr>
</table>

b)

<table>
<tr *ngIf="boat.boatRating>35" *ngFor="let boat of boatArr">
<td>{{boat.boatId}}</td>
<td>{{boat.boatName}}</td>
<td>{{boat.boatRating}}</td>
</tr>
</table>

c)

<table>
<tr *ngFor="let boat of boatArr">
<td>{{boat.boatId}}</td>
<td>{{boat.boatName}}</td>
<td *ngIf="boat.boatRating>35">{{boat.boatRating}}</td>
</tr>
</table>

Options:
a) A and B
b) A Only
c) A and C
d) B Only
MCQ (Q19):
Given array:

boatArr = [
{ boatId: 1, boatName: 'Boat1', boatRating: 30 },
{ boatId: 2, boatName: 'Boat2', boatRating: 32 },
{ boatId: 3, boatName: 'Boat3', boatRating: 34 },
{ boatId: 4, boatName: 'Boat4', boatRating: 37 }
];

Required Output:

boatId boatRating boatName


1 30 (empty)
2 32 (empty)
3 34 (empty)
4 Boat4 37

Notice:

• For first 3 rows ➔ boatRating shown, boatName hidden


• For last row (rating > 35) ➔ boatName shown, boatRating shown

Correct Answer:
B) A Only

Detailed Analysis of Each Option:

Option A:

<table>
<tr *ngFor="let boat of boatArr">
<td>{{boat.boatId}}</td>
<td *ngIf="boat.boatRating>35">{{boat.boatName}}</td>
<td>{{boat.boatRating}}</td>
</tr>
</table>

Correct because:

• Loops correctly over boatArr.


• Displays:
o boatId always
o boatName only if boatRating > 35 (only for Boat4 )
o boatRating always
Minor note:

• In the rows where boatRating ≤ 35, the second <td> (boatName) won't exist ➔ table
might be misaligned visually unless you manage missing <td> carefully.

But for this MCQ, this is the closest and correct approach.

Option B:

<table>
<tr *ngIf="boat.boatRating>35" *ngFor="let boat of boatArr">
<td>{{boat.boatId}}</td>
<td>{{boat.boatName}}</td>
<td>{{boat.boatRating}}</td>
</tr>
</table>

Wrong!

• Error: Multiple structural directives (*ngIf and *ngFor) on the same element ➔
Angular does not allow this .
• Also, even if allowed:
➔ It would render only boats where boatRating > 35, i.e., only Boat4 shown ➔
Not what we want.

Option C:

<table>
<tr *ngFor="let boat of boatArr">
<td>{{boat.boatId}}</td>
<td>{{boat.boatName}}</td>
<td *ngIf="boat.boatRating>35">{{boat.boatRating}}</td>
</tr>
</table>

Wrong!

• boatName will always be shown


• boatRating will be shown only if rating > 35
• Output becomes totally messed up compared to expected table.

Related Concepts (Must Know!):

Concept Key Point


*ngFor Used to iterate over arrays in templates
*ngIf Used to conditionally display elements
Multiple Structural Not allowed on the same HTML tag
Directives
Table Rows Must be properly aligned if dynamic columns are
conditionally shown

Important Rule:
➔ Never put both *ngIf and *ngFor on same element directly.
➔ Use <ng-container> if needed for such combinations.

Key Things to Remember:

• *ngFor for looping, *ngIf inside loop for conditionally showing cells.
• Structural directives like *ngIf and *ngFor can't both exist on same tag (use <ng-
container> if needed).
• If a <td> is conditionally removed, be careful about table alignment!

Pro Tip:
When designing tables with dynamic columns, always check if your rows might "shift" due
to missing <td>. If needed, you can render a blank <td> when the condition fails to maintain
proper structure.

Final Thought:

• Correct answer: B) A Only


• Other options either give error or wrong output!

Question 20
State True or False.

Both template and templateURL must be specified in the metadata, to configure


the template of the corresponding component.

a) True
b) False
MCQ (Q20):
State True or False:
Both template and templateUrl must be specified in the metadata to configure the
template of the corresponding component.

Options:
A) True
B) False

Correct Answer:
B) False

Detailed Explanation:

In Angular, when defining a component’s template:

• You can either use:


o template ➔ To specify the HTML inline (inside the component file itself).
o OR
o templateUrl ➔ To specify the HTML in an external file.

But you must NOT use both at the same time.


Angular expects only one way to define the template.

If you try to specify both template and templateUrl together, it leads to a


compilation error .

Correct examples:

• Inline Template Example:

@Component({
selector: 'app-example',
template: `<h1>Hello from inline template!</h1>`
})
export class ExampleComponent { }

• External Template Example:

@Component({
selector: 'app-example',
templateUrl: './example.component.html'
})
export class ExampleComponent { }
Incorrect (Error) Example:

@Component({
selector: 'app-example',
template: `<h1>Hello</h1>`,
templateUrl: './example.component.html'
})
export class ExampleComponent { }

This would cause an error :


"Component cannot have both template and templateUrl."

Related Concepts (Must Know!):

Concept Key Point


template Used for small, inline HTML
templateUrl Used for larger templates stored in external .html files
Choose only one Must not specify both in the same component

Best Practice:

• Use template if the HTML is very short (1-2 lines).


• Use templateUrl if the HTML is bigger or more complex.

Key Things to Remember:

• You must choose either template or templateUrl, not both.


• Using both causes an Angular error.
• Helps keep components organized and clean!

Pro Tip:
Think like this:
"One way to talk, either inline or external, but not both together!"

Final Thought:

• Correct answer: B) False


• Both template and templateUrl together are NOT allowed.

You might also like