Angular QB
Angular QB
Q1. What is the purpose of the ViewChild decorator in this component class?
@Component({
...
template: '<p #bio></p>'
})
export class UserDetailsComponent {
@ViewChild('bio') bio;
}
It provides access from within the component class to the ElementRef object for
the <p> tag that has the bio template reference variable in the component's
template view.
It indicates that the <p> tag be rendered as a child of the parent view that uses
this component.
It makes the <p> tag in the template support content projection.
It makes the <p> tag visible in the final render. If the #bio was used in the
template and the @ViewChild was not used in the class, then Angular would
automatically hide the <p> tag that has #bio on it.
DigitalOcean - viewchild-access-component
Q2. What method is used to wire up a FormControl to a native DOM input element
in reactive forms?
Add the string name given to the FormControl to an attribute named controls on
the element to indicate what fields it should include.
Use the square bracket binding syntax around the value attribute on the DOM
element and set that equal to an instance of the FormControl.
Use the formControlName directive and set the value equal to the string name
given to the FormControl.
Use the string name given to the FormControl as the value for the DOM element
id attribute.
Angular.io - Reactive Form Groups
Q3. What is the difference between the paramMap and the queryParamMap on
the ActivatedRoute class?
The paramMap is an object literal of the parameters in a route's URL path. The
queryParamMap is an Observable of those same parameters.
The paramMap is an Observable that contains the parameter values that are part
of a route's URL path. The queryParamMap is a method that takes in an array of
keys and is used to find specific parameters in the paramMap.
paramMap is the legacy name from Angular 3. The new name is queryParamMap.
Both are Observables containing values from the requested route's URL string.
The paramMap contains the parameter values that are in the URL path and the
queryParamMap contains the URL query parameters.
StackOverflow
Q4. Based on the following usage of the async pipe, and assuming the users class
field is an Observable, how many subscriptions to the users Observable are being
made?
<h2>Names</h2>
<div *ngFor="let user of users | async">{{ user.name }}</div>
<h2>Ages</h2>
<div *ngFor="let user of users | async">{{ user.age }}</div>
<h2>Genders</h2>
<div *ngFor="let user of users | async">{{ user.gender }}</div>
addOrder(order: Order) {
// Missing line
}
}
this.httpClient.url(this.orderUrl).post(order);
this.httpClient.send(this.orderUrl, order);
this.httpClient.post(this.orderUrl, order);
this.httpClient.post(this.orderUrl, order).subscribe();
Angular.io - Sending data to server
Q6. What is the RouterModule.forRoot method used for?
Registering any providers that you intend to use in routed components.
Registering route definitions at the root application level.
Indicating that Angular should cheer on your routes to be successful.
Declaring that you intend to use routing only at the root level.
O'REILLY
Q7. Which DOM elements will this component metadata selector match on?
@Component({
selector: 'app-user-card',
. . .
})
B
<ul>
<li ngFor="let productName of productNames">{{ productName }}</li>
</ul>
C
<ul>
<li *ngFor="let productName of productNames">{{ productName }}</li>
</ul>
D
<ul>
<? for productName in productNames { ?>
<li>{{ productName }}</li>
<? } ?>
</ul>
{{ 'title' }}
{{ title }}
[title]
The ngIf is shorthand for the other example. When Angular processes that
directive, it writes a div element to the DOM with the hidden property.
They are fundamentally the same.
The ngIf directive does not render the div in the DOM if the expression is false.
The hidden property usage hides the div content in the browser viewport, but
the div is still in the DOM.
The ngIf is valid, but the use of the hidden property is wrong and will throw an
error.
StackOverflow
Q15. How can you disable the submit button when the form has errors in this
template-driven forms example?
<form #userForm="ngForm">
<input type="text" ngModel name="firstName" required />
<input type="text" ngModel name="lastName" required />
<button (click)="submit(userForm.value)">Save</button>
</form>
A
<button (click)="submit(userForm.value)" disable="userForm.invalid">Save</
B
<button (click)="submit(userForm.value)" [disabled]="userForm.invalid">Sav
C
<button (click)="submit(userForm.value)" [ngForm.disabled]="userForm.valid
D
<button (click)="submit(userForm.value)" *ngIf="userForm.valid">Save</butt
The ? is shorthand for the async pipe. The job value must be an Observable.
It is using the safe navigation operator (?) on the job field. If the job field is
undefined, the access to the bossName will be ignored and no error will occur.
There is an error in the template syntax. The ? is not valid here.
It is diplaying the job value if it has one; otherwise it is displaying the bossName.
StackOverflow
Q20. How would you configure a route definition for a UserDetailComponent that
supports the URL path user/23 (where 23 represents the id of the requested
user)?
{ path: 'user/:id', component: UserDetailComponent }
@HostListener('mouseenter')
onMouseEnter() {
this.fontWeight = 'bold';
}
@HostListener('mouseleave')
onMouseLeave() {
this.fontWeight = 'normal';
}
}
They are setting the CalloutDirective.fontWeight field based on whether or not the
mouse is over the DOM element. The HostListener then sets the font-weight CSS
property to the fontWeight value.
They are setting up the directive to check the DOM element that it is on. If it has
event bindings added for mouse enter and leave it will use this code. Otherwise
nothing will happen.
This is an incorrect use of HostListener and HostBinding. The HostListener and
HostBinding decorators do not do anything on directives; they work only when
used on components.
If the DOM element that this directive is placed on has the CSS property font-
weight set on it, the mouseenter and mouseleave events will get raised.
DigitalOcean
Q22. What Angular template syntax can you use on this template-driven form field
to access the field value and check for validation within the template markup?
<input type="text" ngModel name="firstName" required minlength="4" />
<span *ngIf="">Invalid field data</span>
You can make use of a template reference variable and the exportAs feature that
the ngModel directive has.
You can use the ngModel directive in combination with the input field name.
You can use a template reference variable for the HTML input element and then
check the valid property off of that.
It is not possible to get access to the field value with template-driven forms. You
must use reactive forms for that.
1. Angular.io -Show and hide validation error
2. Medium
Q23. What is the value type that will be stored in the headerText template
reference variable in this markup?
<h1 #headerText>User List</h1>
They are the same. Both will result in a new instance of Logger that is bound to
the FormattedLogger token.
The useClass syntax tells the injector to make a new instance of Logger and bind
that instance to the FormattedLogger token. The useExisting syntax refers to an
already existing object instance declared as Logger.
Both of them are wrong. A strong type connot be used for useClass or
useExisting.
They are the same. Both will result in the FormattedLogger token being an alias
for the instance of Logger.
1. Angular.io - Dependency Providers
2. TektutorialHub
Q25. What is the purpose of the data property (seen in the example below) in a
route configuration?
{
path: 'customers',
component: CustomerListComponent,
data: { accountSection: true }
}
a key/value mapping for setting @Input values on the routed component instance
a way to include static, read-only data associated with the route that can be
retrieved from the ActivatedRoute
a property on the route that can be used to load dynamic data for the route
an object that will get auto-injected into the routed component's constructor.
1. TektutorialsHub
2. StackOverflow
Q26. How does the built-in ngIf structural directive change the rendered DOM
based on this template syntax?
@Component({
selector: 'app-product',
template: '<div *ngIf="product">{{ product.name }}</div>',
})
export class ProductComponent {
@Input() product;
}
The <div> acts as a placeholder. If the product class field is "truthy," the <div>
will get replaced by just the product.name value; if not, then nothing will get
rendered.
The <div> will always be rendered, and if the product field is "truthy," the
<div> element will contain the product.name value; otherwise it will render the
<div> element with no value in it.
platformBrowserDynamic().bootstrapModule(AppModule);
Prior to loading the UserComponent, the router will subscribe to the Observable
returned by a resolve method in the UserResolverService. This technique can be
used to get preloaded data for a route.
After the route is done resolving, and the component is loaded and rendered, the
UserResolverService will have a method named user run that will clean up any
open data connections.
There is an error. The correct property name is onResolve.
The UserComponent will have a parameter in its constructor for user, and the
router will handle injecting in a value for that from a call to a user method in the
UserResolverService.
angular.io
Q29. What is the purpose of the ContentChildren decorator in this component
class?
@Component({
. . .
template: '<ng-content></ng-content›'
})
export class TabsListComponent {
@ContentChildren(TabComponent) tabs;
}
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('h1').textContent).toContain(
fixture.componentInstance.title,
);
It tracks any potential Ul changes and will fail the unit test if any are made.
It is used to ensure component template stability across multiple unit tests in the
entire test suite.
It forces Angular to perform change detection, which will render the
UserCardComponent before you can validate its template.
It is used to log change-detection events to the console during unit test runs.
angular.io
Q32. What will the URL segment look like based on the following call to the
Router.navigate method when goToUser is passed the value 15?
/user/15
/user?id=15
/user:15
/user;id=15
angular.io
Q33. When a service is provided for root and is also added to the provider's
configuration for a lazy-loaded module, what instance of that service does the
injector provide to constructors in the lazy-loaded module?
A new instance of that service is created when the module is lazy loaded.
Providing a service of the same type at a lazy-loaded module level is not allowed.
If an instance of the service has not been created at the root level yet. it will
create one there and then use it.
A single instance of that service is always instantiated at root and is the only one
ever used, including within lazy modules.
Q34. What is the HostBinding decorator doing in this directive?
@Directive({
selector: ' [appHighlight] ',
})
export class HighlightDirective {
@HostBinding('class.highlighted') highlight = true;
}
It is adding the CSS class named highlighted to any DOM element that has the
appHighlight directive on it.
HostBinding does not do anything on directives, only on components.
It is specifying if the host element gets the highlighted class added to its class
attribute, then the directive class field highlight will get set to true; and if it is not
added on the host it will get set to false.
It is creating an inline style on the host element with a CSS property named
highlight set to true.
StackOverflow
Q35. In reactive forms, what Angular form class type is used on the native DOM
element to wire it up?
FormArray
FormControl
FormGroup
A
<span *ngIf="username.minLength.invalid"›
Username length is not valid
</span>
B
<input type="text" formControlName="username" [showMinLength]="true"›
C
<span *ngIf="form.get('username').getError('minLength') as minLengthEr
Username must be at least {{ minLengthError.requiredLength }} charac
</span>
D
<input type="text" formControlName="username" #userName="ngModer">
<span *ngIf="userName.errors.minlength"›
Username must be at least {{ userName.errors.minlength.requiredLengt
</span>
Codecraft
Q37. How does the emulated view encapsulation mode handle CSS for a
component?
It renders the CSS exactly how you wrote it without any changes.
It makes use of shadow DOM markup and CSS.
It creates unique attributes for DOM elements and scopes the CSS selectors you
write to those attribute ids.
It renders all of the CSS rules you write as inline CSS on all of the DOM elements
you use them on in the template.
Angular.io
Q38. With the following TestBed setup, what can be used to access the rendered
DOM for the UserCardComponent?
TestBed.configureTestingModule({
declarations: [UserCardComponent],
});
let fixture = TestBed.createComponent(UserCardComponent);
fixture.componentTemplate
fixture.getComponentHtml()
fixture.nativeElement
fixture.componentInstance.template
1. StackOverflow
2. Angular.io
Q39. Given these two components, what will get rendered to the DOM based on
the markup usage?
@Component({
selector: 'app-card',
template: '<h1>Data Card</h1><ng-content></ng-content>'
})
export class CardComponent { }
@Component({
selector: 'app-bio',
template: '<ng-content></ng-content>.
})
export class BioComponent { }
// markup usage:
<app-card><app-bio>Been around for four years.</app-bio></app-card>
A
<app-card>
<h1>Data Card</hl>
<app-bio>
Been around for four years.
</app-bio>
</app-card>
B
<h1>Data Card</h1>
<app-bio>
Been around for four years.
</app-bio>
C
<app-card>
<h1>Data Card</hl>
<ng-content></ng-content>
<app-bio>
Been around for four years.
<ng-content></ng-content>
</app-bio>
</app-card>
D
<app-card>
<h1>Data Card</hl>
</app-card>
Q40. Given the app-title-card component in the code below, what DOM will the
app-user-card component render?
@Component({
selector: 'app-user-card',
template: '<app-title-card></app-title-card><p>Jenny Smith</p>'
})
@Component({
selector: 'app-title-card',
template: '<h1>User Data</hl>'
})
A
<app-user-card>
<app-title-card>
<h1>User Data</h1>
</app-title-card>
<p>Jenny Smith</p>
</app-user-card>
B
<h1>User Data</h1>
<p>Jenny Smith<p>
C
<app-user-card>
<app-title-card></app-title-card>
</app-user-card>
D
<div app-user-card>
<h1 app-title-card>User Data</h1>
<p>Jenny Smith</p>
</div>
Q41. Pick the matching code for the custom provider registration that the @Inject
() decorator is looking for:
constructor(@Inject('Logger') private logger) { }
A
providers: [Logger];
B
providers: [{ provide: 'Logger', useClass: Logger }];
C
@Injectable({
providedln: 'root'
})
D
providers: [{ provide: 'Logger' }];
1. StackOverflow
2. TektutorialHub
3. Angular.io - Dependency Injection In Action
Q42. Which choice best describes the following usage of the HttpClient.get
method in the getsettings class method?
export class SettingsService {
constructor(private httpClient: HttpClient) { }
...
getSettings()
{
return this.httpClient.get<Settings>(this.settingsUrl)
.pipe(
retry(3)
);
}}
The RxJs pipe method is an alias for the subscribe method, so a call to
getSettings will execute the get query. The retry operator is used to tell the
pipe call to retry the get query three times.
It will produce an error at runtime because the pipe method is not available off of
the Httpclient.get call.
Every single call to the getSettings method will result in the Httpclient making
three total get requests to the settingsUrl, which is not ideal because there will
always be two extra calls that are not needed. The retry operator should not be
used in this manner.
When the result of the getSettings method is subscribed to, the HTTP GET call
will be made; if it fails, it will be retried up to three times before it gives up and
returns an error.
1. learnrxjs.io
2. dev.to
Q43. When a service requires some setup to initialize its default state through a
method, how can you make sure that said method is invoked before the service
gets injected anywhere?
Put the logic of that service method into the service constructor instead.
Use a factory provider at the root AppModule level that depends on the service to
call that service method.
it is not possible to do it at application start; you can do it only at a component
level.
Instantiate an instance of the service at the global level (window scope) and then
call that method.
1. Angular.io
2. Stackoverflow
Q44. What statement best describes this usage of the TestBed?
const spy = jasmine.createSpyObj('DataService', ['getUsersFromApi']);
TestBed.configureTestingModule({
providers: [UserService, { provide: DataService, useValue: spy }],
});
const userService = TestBed.get(UserService);
The TestBed is required anytime you want to make use of a spy object in a unit
test for an Angular provider.
The TestBed is being used to test a component's view.
The TestBed scaffolds an NgModule with two providers and handles any
dependency injection. If any Angular class requests the DataService in its
constructor, the TestBed will inject spy in that constructor.
The TestBed is configuring the test runner to tell it to only execute tests for the
two providers listed in its providers array.
All other tests be ignored, including tests that assert results
against one of these providers and a non-defined provider. Although it
will work when multiple providers in this configuration are asserted
against in a single test.
@Output() appTruncate;
constructor(maxLength: number) { }
1. Angular.io
2. StackOverflow
Q47. How can you pass query parameters to this HttpClient.get request?
export class OrderService {
constructor(private httpClient: HttpClient) {}
D
getOrdersByYear(year: number): Observable<Order[]> {
return this.httpClient.addParam('year', year).get<Order[]>(this.orders
}
1. StackOverflow
2. TektutorialHub
Q48. Assuming the DataService has been registered in the providers for the
application, which answer best describes what happens based on this
component's constructor?
@Component({
...
})
export class OrderHistoryComponent {
constructor(private dataService: DataService) {}
...
}
A
<div #inactive>User is not active.</div>
B
<div *ngIf="inactive">
User is not active.
</div>
C
<ng-template #else="inactive">
<div>User is not active.</div>
</ng-template>
D
<ng-template #inactive>
<div>User is not active.</div>
</ng-template>
Angular.io
Q50. What is the correct syntax for a route definition to lazy load a feature
module?
A
{
path: 'users',
lazy: './users/users.module#UsersModule'
}
B
{
path: 'users',
loadChildren: () => import('./users/users.module').then(m => m.UserMod
}
C
{
path: 'users',
loadChildren: './users/users.module#UsersModule'
}
D
{
path: 'users',
module: UsersModule
}
It registers a provider for the service that is available only at the root module level,
not to any children modules.
It registers a provider for the service in the root application injector, making a
single instance of it available throughout the application.
It makes it so the service can be injected only in the bootstrapped component for
the application.
It sets up a compile time rule that allows you to put the service type only in the
providers metadata property of the root NgModule.
Angular.io
Q53. Describe the usage of this code
export interface AppSettings {
title: string;
version: number;
}
export const APP_SETTINGS = new InjectionToken<AppSettings>('app.settings'
submit(form.value)
submit($event)
submit(ngForm.value)
submit(FirstName, lastName)
Q55. What is the purpose of the prelodingStrategy property configuration in
this router code?
RouterModule.forRoot(
...{
preloadingStrategy: PreloadAllModules,
},
);
title="userName"
title="{{ userName }}"
title="{{ 'userName' }}"
The only way to do it is by using the square brackets.
Q57. What is the async pipe doing in this example?
@Component({
selector: 'app-users',
template: '<div *ngFor="let user of users | async">{{ user.name }}</div>
})
export class UsersComponent implements OnInit {
users;
constructor(private httpClient: HttpClient) {}
ngOnInit(): void {
this.users = this.httpClient.get<{ name: string }>('users');
}
}
It is doing nothing, since the async pipe cannot be used in an ngFor statement.
It is configuring the ngFor iteration to support multiple lists of users at the same
time.
It is subscribing to the observable returned from the HttpClient.get method
and unwrapping the returned value so it can be iterated over in the ngFor .
It is allowing all of the users in the users field to be rendered concurrently to the
DOM.
Q58. How would you make use of this directive in markup based on its selector
value
@Directive({
selector: '[appTruncate]'
})
export class TruncateDirective{
. . .
}
Q59. What lifecycle hook can be used on a component to monitor all changes to
@Input values on that component?
ngOnInit
ngChanges
ngAfterInputChange
ngOnChanges
How to detect when an @Input() value changes in Angular?
Q60. What would be an example template syntax usage of this custom pipe?
@Pipe({ name: 'truncate' })
export class TruncatePipe implements PipeTransform {
transform(value: string, maxLength: number, showEllipsis: boolean) {
const newValue = maxLength ? value.substr(0, maxLength) : value;
return showEllipsis ? '${newValue}...' : newValue;
}
}
A
<div *ngIf="location">
<h1>{{ location.name }}</h1>
<p>{{ location.description }}</p>
{{ endNgIf }}
B
<ng-template *ngIf="location">
<h1>{{ location.name }}</h1>
<p>{{ location.description }}</p>
</ng-template>
C
<div *ngIf="location" [display]=" ' hidden' ">
<h1>{{ location.name }}</h1>
<p>{{ location.description }}</p>
</div>
D
<ng-container *ngIf="location">
<h1>{{ location.name }}</h1>
<p>{{ location.description }}</p>
</ng-container>
This code as an error since you cannot use a TypeScript interface for the generic
type on the InjectionToken.
The InjectionToken is used to create a provider token for a non-class dependency.
An object lieteral can be provided as a value for the APP_SETTINGS dependency
provider type that can then be injected into components, services, etc.
The InjectionToken is adding an instance of the AppSettings to the roote provider
via the the InjectionToken constructor call, making it auto available to all
NgModules, services, and componentts throughtout the Angular application
without the need to inject it anywhere.
The InjectionToken is used to create a dynamic decorator for the AppSettings that
can be sed on constructor parameters via an @AppSettings decorator.
Q64. What Angular utilities, if any, are required to unit test a service with no
constructor dependencies?
By.css() helper method is needed
A text fixture is required to run the service for the unit test.
None. A service can be instantiated and unit tested on its own.
The TestBed class iss needed to instantiate the service.
Angular unit tests - recheck answers
Q65. What is the difference between the CanActivate and the CanLoad route
guards?
CanActivate is used to check access. CanLoad is used to preload data for the
route.
CanLoad is used at app startup to allow or deny routes to be added to the route
table. CanActivate is used to manage access to routes at the time they are
requested.
CanActivate and CanLoad do the exact same thing.
CanLoad prevents an entire NgModule from being delivered and loaded.
CanActivate stops routing to a component in that NgModule, but that module is
still loaded.
CanActivate vs Canload CanActivate prevents access on routes, CanLoad prevents
lazy loading.
Q66. What is the outlet property used for in this router definition object?
{
path: 'document',
component: DocumentComponent,
outlet: 'document-box'
}
it will locate all instancess of in the DOM and inser a DocumentComponent
element into them on route navigation.
It declares that the DocumentComponent can be used as a child to a < element in
addition ot being routed to.
It us used to target a element with the name attribute matching the string value as
the location for the DocumentComponent to be rendered when routed to.
It is a source of power for the router. (definitely not the answer :P)
Angular-outlet - recheck answer
Q67. In this template syntax, every time the items property is changed (added to,
removed from, etc.), the ngFor structural directive re-runs its logic for all DOM
elements in the loop. What syntax can be used to make this more performant?
<div *ngFor="let item of items">
{{ item.id }} - {{ item.name }}
</div>
ActivatedRoute
CurrentRoute
UrlPath
@Inject('id')
Common Routing Tasks
Q74. With the following reactive form markup, what would you add to wire up a
call to an onSubmit class method?
<form [formGroup]="form">
<input type="text" formControlName="username" />
<button type="submit" [disabled]="form. invalid">Submit</button>
</form>
Angular - NgClass
Q76. Which answer best explains the usage of ngModel in this template code?
<input [(ngModel)]="user.name" />
[]
<span class="{{ isActive ? 'is-active' : '' }}" class="{{ canToggle ? 'can
Employed
</span>
[x]
<span [class.active]="isActive" [class.can-toggle]="canToggle"> Employed <
[]
<span [styles.class.active]="isActive" [styles.class.can-toggle]="canToggl
[]
<span [css.class.active]="isActive" [css.class.can-toggle]="canToggle"> Em
Q79. In this directive decorator example, what is the purpose of the multi property
in the provider object literal?
@Directive({
selector: '[customValidator]',
providers: [
{
provide: NG_VALIDATORS,
useExisting: CustomValidatorDirective,
multi: true,
},
],
})
export class CustomValidatorDirective implements Validator {}