Angular Quiz

Description

Angular Quiz
Monte Crucis
Flashcards by Monte Crucis, updated 4 days ago
Monte Crucis
Created by Monte Crucis 14 days ago
1
0
1 2 3 4 5 (0)

Resource summary

Question Answer
Which CLI command should we run to compile and serve our project locally in development mode? ng serve ng build ng development ng deploy ng serve
What does Angular refer to? The latest version of the framework (Angular 2+) Version 3 of the framework Version 16 of the framework Version 1 of the framework The latest version of the framework (Angular 2+)
Which of the following file names does not follow the Angular style-guide conventions? uppercase-pipe.ts highlight-all.directive.ts name.service.ts app.component.ts uppercase-pipe.ts
Which one of the following is not a valid Angular CLI command? ng fix ng build ng add ng test ng fix
Which one of these concepts does not exist in the Angular framework? Standalone components Structural directives Redux reducers NgModules Redux reducers
Which of the following statements is true? Services link components to server-side HTML templates Pipes are used to format data such as dates and numbers Component libraries cannot be customized to our needs Directives are a way to interact with server-side APIs Pipes are used to format data such as dates and numbers
What's the main language of the Angular framework? JSP AppScript JavaScript TypeScript TypeScript
When do we need to create or use Angular services? To implement business logic To filter data displayed in a component To generate, serve, compile, test, and build Angular code To interact with the browser To implement business logic
What is the difference between an interface and a class in TypeScript? There is no difference between an interface and a class in TypeScript. An interface is a contract that defines the properties and methods that an object must have. A class is a blueprint for creating objects. A class is a contract that defines the properties and methods that an object must have. An interface is a blueprint for creating objects None of these answers are correct. An interface is a contract that defines the properties and methods that an object must have. A class is a blueprint for creating objects.
According to the following declaration: let users = ["a", "b", "c"]; What is the type of users? Array None of the above string[] char[] string[]
What is the type of the variable `myVar` if it is declared as follows: let myVar: string | number; number string This syntax doesn't work string or number string or number
Which of the following code examples does not compile? let a: number = 42; const c: number = "21"; var a = 42; let c = 'number'; const c: number = "21";
ngIf shorthand syntax <div *ngIf="condition">Content to render when condition is true.</div>
ngIf expanded syntax: <ng-template [ngIf]="condition"> <div>Content to render when condition is true.</div> </ng-template>
ngIf with an "else" block: <div *ngIf="condition; else elseBlock"> Content to render when condition is true. </div> <ng-template #elseBlock> Content to render when condition is false. </ng-template>
ngIf form with "then" and "else" blocks: <div *ngIf="condition; then thenBlock else elseBlock"> </div> <ng-template #thenBlock> Content to render when condition is true. </ng-template> <ng-template #elseBlock> Content to render when condition is false. </ng-template>
ngIf with storing the value locally: <div *ngIf="condition as value; else elseBlock">{{value}}</div> <ng-template #elseBlock> Content to render when value is null. </ng-template>
ngFor shorthand syntax <li *ngFor="let item of items; index as i; trackBy: trackByFn" >...</li>
ngFor expanded syntax <ng-template ngFor let-item [ngForOf]="items" let-i="index" [ngForTrackBy]="trackByFn"> <li>...</li> </ng-template>
ng-template is a directive in Angular that allows you to define a template that can be rendered conditionally or dynamically. The contents of an ng-template are not rendered in the DOM until explicitly told to do so, usually by directives like *ngIf, *ngFor, or other structural directives.
switch case default @switch (userPermissions) { @case ('admin') { <app-admin-dashboard /> } @case ('reviewer') { <app-reviewer-dashboard /> } @case ('editor') { <app-editor-dashboard /> } @default { <app-viewer-dashboard /> } }
@for with @empty @for (item of items; track item.name) { <li> {{ item.name }}</li> } @empty { <li aria-hidden="true"> There are no items. </li> }
Contextual variable $count Number of items in a collection iterated over
Contextual variable $index Index of the current row
Contextual variable $first Whether the current row is the first row
Contextual variable $last Whether the current row is the last row
Contextual variable $even Whether the current row index is even
Contextual variable $odd Whether the current row index is odd
All context variables usage example import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: <ul> <li *ngFor="let item of items; let i = index; let isFirst = first; let isLast = last; let isEven = even; let isOdd = odd"> <span *ngIf="isFirst"> [First Item] </span> <span *ngIf="isLast"> [Last Item] </span> <span *ngIf="isEven"> [Even Index] </span> <span *ngIf="isOdd"> [Odd Index] </span> Item {{ i + 1 }}: {{ item }} </li> </ul> }) export class AppComponent { items: string[] = ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5']; } <li *ngFor="let item of items; let i = index; let isFirst = first; let isLast = last; let isEven = even; let isOdd = odd">
Structural directives Structural directives are directives applied to an <ng-template> element that conditionally or repeatedly render the content of that <ng-template>.
Structural directive select <ng-template select let-data [selectFrom]="source"> <p>The data is: {{ data }}</p> </ng-template>
Structural directive select shorthand <p class="data-view" *select="let data from source"> The data is: {{data}} </p>
Binding key in <p class="data-view" *select="let data from source">The data is: {{data}}</p> The first part of the *select expression is let data, which declares a template variable data. Since no assignment follows, the template variable is bound to the template context property $implicit. The second piece of syntax is a key-expression pair, from source. from is a binding key and source is a regular template expression. Binding keys are mapped to properties by transforming them to PascalCase and prepending the structural directive selector. The from key is mapped to selectFrom, which is then bound to the expression source. This is why many structural directives will have inputs that are all prefixed with the structural directive's selector.
One structural directive per element You can only apply one structural directive per element when using the shorthand syntax. This is because there is only one <ng-template> element onto which that directive gets unwrapped. Multiple directives would require multiple nested <ng-template>, and it's unclear which directive should be first. <ng-container> can be used when to create wrapper layers when multiple structural directives need to be applied around the same physical DOM element or component, which allows the user to define the nested structure.
creating the SelectDirective ng generate directive select
ng generate directive select import {Directive, TemplateRef, ViewContainerRef} from '@angular/core'; @Directive({ selector: '[select]', }) export class SelectDirective { private templateRef = inject(TemplateRef); private viewContainerRef = inject(ViewContainerRef); }
Which @for block option is required? count track trackBy $index track
Which of the following options is not a valid Angular selector? app-header ng-header [header]:not(div) .header ng-header
What is the decorator used to pass data to a component? @Data() @Input() @Model() @Prop() @Input()
Which of these HTML template examples would automatically render the latest value of data when data changes? (click)="data" ([ngModel])=”data” [value]="data" {data} [value]="data"
Which of the following correctly sets a new value for a Signal called mySig? mySig = 21 mySig() = 21 mySig.set(21) mySig.setValue(21) mySig.set(21)
Which component decorator option turns a component into a standalone feature? module: false changeDetectionStrategy: Standalone ngModule: false standalone: true standalone: true
What is the decorator used to pass data to a component? @Prop() @Property() @Input() @Data() @Input()
Is there anything wrong with the following template? <button (click)="extendDateFor(selection)" disabled="selection.isEmpty()"> Extend date for selection </button> No, the code looks correct. Yes, curly braces {{ }} are missing for the expression bindings. Yes, the click listener syntax should be (onClick). Yes, square brackets are missing around disabled. It should be [disabled] instead. Yes, square brackets are missing around disabled. It should be [disabled] instead.
What is the difference between an interface and a class in TypeScript? A class is a contract that defines the properties and methods that an object must have. An interface is a blueprint for creating objects There is no difference between an interface and a class in TypeScript. None of these answers are correct. An interface is a contract that defines the properties and methods that an object must have. A class is a blueprint for creating objects. An interface is a contract that defines the properties and methods that an object must have. A class is a blueprint for creating objects.
According to the following declaration: let users = ["a", "b", "c"]; What is the type of users? string[] None of the above char[] Array string[]
What is the type of the variable myVar if it is declared as follows: let myVar: string | number; string number This syntax doesn't work string or number string or number
Which of the following code examples does not compile? const c: number = "21"; var a = 42; let c = 'number'; let a: number = 42; const c: number = "21";
Which of the following is not an Angular directive from @angular/common? ngBind ngIf ngSwitch ngClass ngBind
Which of these options is the correct syntax for pipe parameters? {{ amount | currency : ‘USD’ }} {{ amount | currency :: ‘$’ }} {{ amount | currency | ‘USD’ }} None of the above - all are incorrect {{ amount | currency : ‘USD’ }}
What is a directive? A way to inject services and business logic A component with no HTML template A pipe with an HTML template A component with no selector A component with no HTML template
Which one of these pipes does not exist in the Angular framework? json format titlecase currency format
In Angular, which of the following decorators is used to register a class as a service? @Inject @Service @Injectable @NgService @Injectable
Can the following class be injected into a component as-is? import { Injectable } from "@angular/core"; import { HttpClient } from "@angular/common/http"; @Injectable() export class CartService { constructor(private http: HttpClient) {} getCartContents() { // Some code } } No, it does not have the @Service decorator Yes No, that code does not compile No, it has to be added to an array of providers first No, it has to be added to an array of providers first
According to the following code, how many instances of TokenService can we have in an Angular application? (assuming there's no other dependency injection configuration anywhere else for that service) @Injectable({ providedIn: "root", }) export class TokenService { // ... (rest of the class implementation) } It could be any number of instances Zero or one One One per module Zero or one
What is the name of the service used to make HTTP requests with Angular? $resource HttpClient HttpService Fetch HttpClient
Which of the following properties is NOT a valid property of an Angular FormControl: dirty valid async untouched async
What is the name of the Angular service used to create reactive forms? FormFactory FormBuilder FormControl FormService FormBuilder
Which of these statements is correct regarding template-driven forms? They are configured only in HTML templates They are configured with TypeScript code They enable RxJs subscriptions to any value and state change in the form They require simple functions for form validation They are configured only in HTML templates
Which of the following CSS classes is NOT automatically managed by Angular forms? ng-invalid ng-dirty ng-select ng-touched ng-select
In Angular, what is the purpose of the tag? It defines the root component of the application It's a way to embed an iframe in an Angular application It specifies navigation links for the user It indicates where routed components will be rendered It indicates where routed components will be rendered
Considering the following router config, which component will be rendered when a user navigates to /products/21? RouterModule.forRoot([ { path: "", component: ProductListComponent }, { path: "products/:productId", component: ProductDetailsComponent }, ]); ProductDetailsComponent None; there is no mapping for that route ProductListComponent A 404 page would show up ProductDetailsComponent
Which of the following is an existing guard function that can be used with the Angular router? CanActivate CanInit CannotActivate CanNavigate CanActivate
What is the name of the Angular service used to manage routing? RouterOutlet ActivatedRoute Router RouterService Router
What is the recommended approach when using multiple Signals in a single component? - A) Use global variables for signals - B) Combine similar Signals into one - C) Utilize composed signals for better readability - D) Manage Signals in a service to share state D) Manage Signals in a service to share state
What type of value can a Signal hold in Angular? - A) Only primitive values - B) Only objects - C) Any type of value (primitive, objects, arrays, etc.) - D) String values only C) Any type of value (primitive, objects, arrays, etc.)
What is a common pattern observed when using Signals in Angular? - A) Mixing signals with reactive forms - B) Using signals only for component state management - C) Combining signals with observables - D) Having signals for only simple values C) Combining signals with observables
What is the default behavior of a Signal in Angular with respect to change detection? - A) Signals do not trigger change detection in Angular. - B) Signals trigger change detection only on subscription. - C) Signals automatically trigger change detection when their value is updated. - D) Signals require manual triggers for change detection. C) Signals automatically trigger change detection when their value is updated.
Which of the following correctly resets a writable signal to a new value? - A) `signal.reset(newValue);` - B) `signal.set(newValue);` - C) `signal.update(newValue);` - D) `signal.value = newValue;` B) `signal.set(newValue);`
How can you react to changes in a Signal in Angular? - A) By subscribing using `.subscribe()` - B) By using `ngFor` - C) By using `*ngIf` - D) Automatically in the template with interpolation D) Automatically in the template with interpolation
Which lifecycle hook is most common for reading Signals? - A) ngOnInit - B) ngAfterViewInit - C) ngOnDestroy - D) ngOnChanges A) ngOnInit
How do you create a writable signal in Angular? - A) `let signal = signal(writableValue);` - B) `let signal = new Signal(writableValue);` - C) `let signal = writableSignal(writableValue);` - D) `let signal = createSignal(writableValue);` C) `let signal = writableSignal(writableValue);`
Which of the following is a key advantage of using Signals in Angular? - A) It allows hiding components. - B) It provides built-in form validation. - C) It simplifies managing state changes. - D) It automatically generates HTTP service endpoints. C) It simplifies managing state changes.
What are Angular Signals primarily used for? - A) To manage Angular services - B) To handle state and reactivity - C) To perform HTTP requests - D) To define routes B) To handle state and reactivity
What is the primary function of an Angular Signal? A: To directly manipulate the DOM outside of Angular's change detection. B: To provide a wrapper around a value that notifies consumers when it changes, enabling fine-grained reactivity. C: To replace RxJS Observables for all asynchronous operations. D: To define the visual structure of a component using template syntax. B: To provide a wrapper around a value that notifies consumers when it changes, enabling fine-grained reactivity. Signals are reactive primitives; they hold a value and notify dependent consumers (like components or other signals) when that value is updated, forming the basis of Angular's new reactivity model. Example: `const count = signal(0); // Reading: count(); // Setting: count.set(1);`
Which of the following CORRECTLY shows how to create and update a writable signal in an Angular component? A: this.counter = signal(0); this.counter.setValue(1); B: this.counter = new Signal(0); this.counter.update(1); C: this.counter = signal(0); this.counter.set(1); D: this.counter = createSignal(0); this.counter(1); C: this.counter = signal(0); this.counter.set(1); Explanation: Writable signals are created using the signal() function with an initial value. They can be updated using the .set() method to assign a new value directly or .update() to transform the current value. Option A is incorrect (no setValue method), B is incorrect (not created with new), and D is incorrect (Angular uses signal(), not createSignal()).
How does a `computed()` signal primarily differ from a writable `signal()`? A: Computed signals can only hold primitive values, while writable signals can hold objects. B: Computed signals update their value immediately when dependencies change, whereas writable signals update asynchronously. C: Computed signals derive their value from other signals and are lazily evaluated and memoized, while writable signals are directly updated via `.set()` or `.update()`. D: Writable signals automatically track dependencies, while computed signals require manual dependency registration. C: Computed signals derive their value from other signals and are lazily evaluated and memoized, while writable signals are directly updated via `.set()` or `.update()`. Explanation: Computed signals derive their state reactively from other signals. They don't recalculate unless read and their dependencies have changed (lazy evaluation), and they cache the result (memoization). Writable signals hold state that is changed imperatively. Example: `const price = signal(100); const taxRate = signal(0.1); const priceWithTax = computed(() => price() * (1 + taxRate()));`
In a real-world application, when would you use a computed signal INSTEAD OF directly calculating a value in the template? A: When you need to display the current time that updates every second. B: When you have a complex calculation based on signals that's used in multiple places in your template. C: When you need to trigger an HTTP request whenever a signal changes. D: When you need to update multiple signals simultaneously. B: When you have a complex calculation based on signals that's used in multiple places in your template.
In an Angular component using `ChangeDetectionStrategy.OnPush`, what occurs when a signal read within its template is updated? A: The component and all its ancestors are automatically marked for check. B: Only the specific DOM element bound to the signal is updated, bypassing component change detection. C: The component is automatically marked for check, ensuring it re-renders to reflect the signal's new value. D: An error is thrown because signals cannot be used directly in OnPush component templates. C: The component is automatically marked for check, ensuring it re-renders to reflect the signal's new value.
Which scenario is the MOST appropriate use case for an `effect()` in Angular Signals? A: Calculating a derived value based on one or more signals to display in the template. B: Creating a new signal whose value depends on another signal. C: Logging signal value changes to the console or synchronizing signal state with `localStorage`. D: Binding a signal's value to an input property of a child component. C: Logging signal value changes to the console or synchronizing signal state with `localStorage`.
How do Signals compare to RxJS Observables in Angular applications? A: Signals completely replace RxJS and should be used for all reactive programming needs. B: Signals are for synchronous state management while RxJS excels at handling asynchronous streams, transformations, and complex event patterns. C: Signals are exclusively for components, while RxJS is only for services. D: Signals work with templates but RxJS doesn't work with Angular's binding system. B: Signals are for synchronous state management while RxJS excels at handling asynchronous streams, transformations, and complex event patterns.
What happens when you modify a deeply nested property within an object held by a signal without using `.set()` or `.update()`? A: The signal automatically detects the change and notifies all consumers. B: The signal won't notify consumers because it uses reference equality for objects by default. C: Angular throws a runtime error prompting you to use an immutable update pattern. D: The signal will warn you in the console but still update dependents. B: The signal won't notify consumers because it uses reference equality for objects by default.
Why is using `computed()` generally preferred over `effect()` for deriving state that will be used elsewhere in the application or template? A: Effects run asynchronously, which is unsuitable for state used in templates. B: Computed signals are lazily evaluated and memoized, making them more efficient for state derivation than effects which run eagerly. C: Effects cannot read other signals, only writable signals can. D: Computed signals automatically clean up their dependencies, whereas effects can cause memory leaks. B: Computed signals are lazily evaluated and memoized, making them more efficient for state derivation than effects which run eagerly.
What is the main purpose of the `linkedSignal` function (currently in Developer Preview)? A: To create a signal that mirrors an RxJS Observable. B: To establish a two-way data binding between a signal and a form control. C: To create a signal whose state is intrinsically derived from another signal or computation, ensuring it always reflects the source. D: To link multiple components together using a shared signal state. C: To create a signal whose state is intrinsically derived from another signal or computation, ensuring it always reflects the source.
What primary problem does the experimental `resource()` function aim to solve within Angular's signal ecosystem? A: Managing complex component hierarchies. B: Improving the performance of computed signals with many dependencies. C: Integrating and managing state derived from asynchronous operations (like API calls) directly into the signal graph. D: Providing a way to create signals that are automatically persisted to browser storage. C: Integrating and managing state derived from asynchronous operations (like API calls) directly into the signal graph.
How would you properly test a component that uses signals in Angular? A: You can't test components with signals using Angular's TestBed. B: Use spyOn to mock signals and manually trigger change detection between signal updates. C: Directly modify component properties and use detectChanges() to update the view, ignoring signals completely. D: Interact with signals normally through component methods and use TestBed's change detection to see reflected updates in the DOM. D: Interact with signals normally through component methods and use TestBed's change detection to see reflected updates in the DOM.
What is the effect of reading a signal's value inside the `untracked()` function? A: It forces the signal to update its value immediately. B: It prevents the current reactive context (like a `computed` or `effect`) from establishing a dependency on that signal. C: It converts the signal into a non-reactive static value. D: It throws an error if used outside of an `effect`. B: It prevents the current reactive context (like a `computed` or `effect`) from establishing a dependency on that signal.
Which of the following is a valid performance optimization when working with signals that hold large arrays or objects? A: Always use JSON.stringify to compare objects for equality before updating signals. B: Use structural sharing techniques when updating, modifying only the parts that changed while reusing unchanged portions. C: Convert all signals to RxJS Observables for better performance with complex objects. D: Split large objects into individual signals for each property to improve change detection. B: Use structural sharing techniques when updating, modifying only the parts that changed while reusing unchanged portions.
Reactive vs. Template Driven Forms: Setup of Form model? Explicit, created in component class vs. Implicit, created by directives
Reactive vs. Template Driven Forms: Data model? Structured and immutable vs. Unstructured and mutable
Reactive vs. Template Driven Forms: Data flow? Synchronous vs. Asynchronous
Reactive vs. Template Driven Forms: Form validation? Functions vs. Directives
what does ng build do? ng build is a command in Angular that compiles and bundles your application's code, along with its dependencies, into a distributable format. The resulting output is a set of files that can be deployed to a production environment.
Show full summary Hide full summary

0 comments

There are no comments, be the first and leave one below:

Similar

Angular
Kingsley Bawuah
Angular Nuts and Bolts
James Drummond
Scope and Inheritance in Angular
James Drummond
Angular application scaffolding
James Drummond
Fluxo buscaCliente
Alex José Silva
Directives and scope
James Drummond
FE Web Applications Components
Juan Carlos Joya Carvajal
Angular Concept questions and answers
Abinaya Murugaiyan
Angular
Jacinto Canek
How Angular works
James Drummond