Angular

What is the purpose of the ViewChild decorator in this component class?

angularjs @Component({ ... template: '<p #bio></p>' }) export class UserDetailsComponent { @ViewChild('bio') bio; }

1.

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.

2.

It indicates that the `<p>` tag be rendered as a child of the parent view that uses this component.

3.

It makes the `<p>` tag in the template support content projection.

4.

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.

Q 1 / 57

Angular

What method is used to wire up a FormControl to a native DOM input element in reactive forms?

1.

Add the string name given to the FormControl to an attribute named controls on the <form> element to indicate what fields it should include.

2.

Use the square bracket binding syntax around the value attribute on the DOM element and set that equal to an instance of the FormControl.

3.

Use the formControlName directive and set the value equal to the string name given to the FormControl.

4.

Use the string name given to the FormControl as the value for the DOM element id attribute.

Q 2 / 57

Angular

What is the difference between the `paramMap` and the `queryParamMap` on the `ActivatedRoute` class?

1.

The paramMap is an object literal of the parameters in a route's URL path. The queryParamMap is an Observable of those same parameters.

2.

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.

3.

paramMap is the legacy name from Angular 3. The new name is queryParamMap.

4.

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.

Q 3 / 57

Angular

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?

html <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>

1.

None. The async pipe does not subscribe automatically.

2.

None. The template syntax is not correct.

3.

Three. There is one for each async pipe.

4.

One. The async pipe caches Observables by type internally.

Q 4 / 57

Angular

How can you use the HttpClient to send a POST request to an endpoint from within an addOrder function in this OrderService?

angularjs export class OrderService { constructor(private httpClient: HttpClient) { } addOrder(order: Order) { // Missing line } }

1.

this.httpClient.url(this.orderUrl).post(order);

2.

this.httpClient.send(this.orderUrl, order);

3.

this.httpClient.post<Order>(this.orderUrl, order);

4.

this.httpClient.post<Order>(this.orderUrl, order).subscribe();

Q 5 / 57

Angular

What is the RouterModule.forRoot method used for?

1.

Registering any providers that you intend to use in routed components.

2.

Registering route definitions at the root application level.

3.

Indicating that Angular should cheer on your routes to be successful.

4.

Declaring that you intend to use routing only at the root level.

Q 6 / 57

Angular

Which DOM elements will this component metadata selector match on?

angularjs @Component({ selector: 'app-user-card', . . . })

1.

Any element with the attribute app-user-card, such as `<div app-user-card></div>`.

2.

The first instance of `<app-user-card></app-user-card>`.

3.

All instances of `<app-user-card></app-user-card>`.

4.

All instances of `<user-card></user-card>`.

Q 7 / 57

Angular

What is the correct template syntax for using the built-in ngFor structural directive to render out a list of productNames?

html <ul> <li [ngFor]="let productName of productNames">{{ productName }}</li> </ul> html <ul> <li ngFor="let productName of productNames">{{ productName }}</li> </ul> html <ul> <li *ngFor="let productName of productNames">{{ productName }}</li> </ul> html <ul> <? for productName in productNames { ?> <li>{{ productName }}</li> <? } ?> </ul>

1.

html <ul> <li [ngFor]="let productName of productNames">{{ productName }}</li> </ul>

2.

html <ul> <li ngFor="let productName of productNames">{{ productName }}</li> </ul>

3.

html <ul> <li *ngFor="let productName of productNames">{{ productName }}</li> </ul>

4.

html <ul> <? for productName in productNames { ?> <li>{{ productName }}</li> <? } ?> </ul>

Q 8 / 57

Angular

What are the two component decorator metadata properties used to set up CSS styles for a component?

1.

viewEncapsulation and viewEncapsulationFiles.

2.

There is only one and it is the property named css.

3.

css and cssUrl.

4.

styles and styleUrls.

Q 9 / 57

Angular

With the following component class, what template syntax would you use in the template to display the value of the title class field?

javascript @Component({ selector: 'app-title-card', template: '', }) class TitleCardComponent { title = 'User Data'; }

1.

`{{ 'title' }}`

2.

`{{ title }}`

3.

`[title]`

4.

A class field cannot be displayed in a template via the template syntax.

Q 10 / 57

Angular

What is the purpose of the valueChanges method on a FormControl?

1.

It is used to configure what values are allowed for the control.

2.

It is used to change the value of a control to a new value. You would call that method and pass in the new value for the form field. It even supports passing in an array of values that can be set over time.

3.

It returns a Boolean based on if the value of the control is different from the value with which it was initialized.

4.

It is an observable that emits every time the value of the control changes, so you can react to new values and make logic decisions at that time.

Q 11 / 57

Angular

What directive is used to link an `<a>` tag to routing?

1.

routeTo

2.

routerLink

3.

routePath

4.

appLink

Q 12 / 57

Angular

What is the Output decorator used for in this component class?

javascript @Component({ selector: 'app-shopping-cart', . . . }) export class ShoppingCartComponent { @Output() itemTotalChanged = new EventEmitter(); }

1.

It makes the `itemTotalChanged` class field public.

2.

It provides a way to bind values to the `itemTotalChanged` class field, like so: `<app-shopping-cart [itemTotalChanged]="newTotal"></app-shopping-cart>`.

3.

It provides a way to bind events to the `itemTotalChanged` class field, like so: `<app-shopping-cart (itemTotalChanged)="logNewTotal($event)"></app-shopping-cart>`.

4.

It is simply a way to put a comment in front of a class field for documentation.

Q 13 / 57

Angular

What is the difference between these two markup examples for conditionally handling display?

html <div *ngIf="isVisible">Active</div> <div [hidden]="!isVisible">Active</div>

1.

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.

2.

They are fundamentally the same.

3.

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.

4.

The `ngIf` is valid, but the use of the `hidden` property is wrong and will throw an error.

Q 14 / 57

Angular

How can you disable the submit button when the form has errors in this template-driven forms example?

html <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> html <button (click)="submit(userForm.value)" disable="userForm.invalid">Save</button> html <button (click)="submit(userForm.value)" [disabled]="userForm.invalid">Save</button> html <button (click)="submit(userForm.value)" [ngForm.disabled]="userForm.valid">Save</button> html <button (click)="submit(userForm.value)" *ngIf="userForm.valid">Save</button>

1.

html <button (click)="submit(userForm.value)" disable="userForm.invalid">Save</button>

2.

html <button (click)="submit(userForm.value)" [disabled]="userForm.invalid">Save</button>

3.

html <button (click)="submit(userForm.value)" [ngForm.disabled]="userForm.valid">Save</button>

4.

html <button (click)="submit(userForm.value)" *ngIf="userForm.valid">Save</button>

Q 15 / 57

Angular

You want to see what files would be generated by creating a new contact-card component. Which command would you use?

1.

ng generate component contact-card --dry-run

2.

ng generate component contact-card --no-files

3.

ng generate component component --dry

4.

ng generate component --exclude

Q 16 / 57

Angular

Based on the following component, what template syntax would you use to bind the TitleCardComponent's titleText field to the h1 element title property?

javascript @Component({ selector: 'app-title-card', template: '<h1 title="User Data"> {{titleText}}</h1>', }) export class TitleCardComponent { titleText = 'User Data'; }

1.

`<h1 data-title="titleText">{{ titleText }}</h1>`

2.

`<h1 title="titleText">{{ titleText }}</h1>`

3.

`<h1 [title]="titleText">{{ titleText }}</h1>`

4.

`<h1 titleText>{{ titleText }}</h1>`

Q 17 / 57

Angular

What are Angular lifecycle hooks?

1.

loggers for tracking the health of an Angular app

2.

providers that can be used to track the instances of components

3.

built-in pipes that can be used in templates for DOM events

4.

reserved named methods for components and directives that Angular will call during set times in its execution, and can be used to tap into those lifecycle moments

Q 18 / 57

Angular

Pick the best description for this template syntax code:

html <span>Boss: {{job?.bossName}} </span>

1.

The ? is shorthand for the async pipe. The job value must be an Observable.

2.

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.

3.

There is an error in the template syntax. The ? is not valid here.

4.

It is diplaying the job value if it has one; otherwise it is displaying the bossName.

Q 19 / 57

Angular

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)?

1.

`{ path: 'user/:id', component: UserDetailComponent }`

2.

`{ url: 'user/:id', routedComponent: UserDetailComponent }`

3.

`{ routedPath: 'user/:id', component: UserDetailComponent }`

4.

`{ destination: new UserDetailComponent(), route: 'user/:id' }`

Q 20 / 57

Angular

What are the HostListener decorators and the HostBinding decorator doing in this directive?

javascript @Directive({ selector: '[appCallout]', }) export class CalloutDirective { @HostBinding('style.font-weight') fontWeight = 'normal'; @HostListener('mouseenter') onMouseEnter() { this.fontWeight = 'bold'; } @HostListener('mouseleave') onMouseLeave() { this.fontWeight = 'normal'; } }

1.

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.

2.

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.

3.

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.

4.

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.

Q 21 / 57

Angular

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?

html <input type="text" ngModel name="firstName" required minlength="4" /> <span *ngIf="">Invalid field data</span>

1.

You can make use of a template reference variable and the exportAs feature that the ngModel directive has.

2.

You can use the ngModel directive in combination with the input field name.

3.

You can use a template reference variable for the HTML input element and then check the valid property off of that.

4.

It is not possible to get access to the field value with template-driven forms. You must use reactive forms for that.

Q 22 / 57

Angular

What is the value type that will be stored in the headerText template reference variable in this markup?

html <h1 #headerText>User List</h1>

1.

an Angular ElementRef, a wrapper around a native element

2.

the inner text of the `<h1>` element

3.

a header component class

4.

the native DOM element type of HTMLHeadingElement

Q 23 / 57

Angular

What is the difference, if any, of the resulting code logic based on these two provider configurations?

javascript

1.

They are the same. Both will result in a new instance of Logger that is bound to the FormattedLogger token.

2.

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.

3.

Both of them are wrong. A strong type connot be used for useClass or useExisting.

4.

They are the same. Both will result in the FormattedLogger token being an alias for the instance of Logger.

Q 24 / 57

Angular

What is the purpose of the data property (seen in the example below) in a route configuration?

javascript { path: 'customers', component: CustomerListComponent, data: { accountSection: true } }

1.

a key/value mapping for setting @Input values on the routed component instance

2.

a way to include static, read-only data associated with the route that can be retrieved from the ActivatedRoute

3.

a property on the route that can be used to load dynamic data for the route

4.

an object that will get auto-injected into the routed component's constructor.

Q 25 / 57

Angular

How does the built-in `ngIf` structural directive change the rendered DOM based on this template syntax?

javascript @Component({ selector: 'app-product', template: '<div *ngIf="product">{{ product.name }}</div>', }) export class ProductComponent { @Input() product; }

1.

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.

2.

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.

3.

It produces an error, since ngIf is not a built-in structural directive.

4.

If the product class field is "truthy," then the rendered DOM will include the `<div>` with the value of the `product.name` field. If it is not "truthy,' the rendered DOM will not contain the `<div>` element.

Q 26 / 57

Angular

What does this code accomplish?

javascript @NgModule({ declarations: [AppComponent], imports: [BrowserModule], bootstrap: [AppComponent], }) export class AppModule {} platformBrowserDynamic().bootstrapModule(AppModule);

1.

It executes a unit test for an NgModule.

2.

It provides a way to code the document structure of an Angular application. The @NgModule is a form of inline code commenting that gets ignored by the TypeScript compiler but will show up with special formatting in code editor applications.

3.

It declares an Angular module named AppModule and makes it available for lazy loading throughout the application.

4.

It declares an Angular module named AppModule that contains a bootstrapped component named AppComponent. Then it registers that module with Angular, so the app can start up.

Q 27 / 57

Angular

Which choice best describes what the _resolve_ property does in this route configuration?

javascript { path: ':id', component: UserComponent, resolve: { user: UserResolverService } }

1.

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_.

2.

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.

3.

There is an error. The correct property name is _onResolve_.

4.

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_.

Q 28 / 57

Angular

What is the purpose of the ContentChildren decorator in this component class?

javascript @Component({ . . . template: '<ng-content></ng-content›' }) export class TabsListComponent { @ContentChildren(TabComponent) tabs; }

1.

If any _TabsComponent_ elements are added to the _TabsListComponent_ template, they will get put into the <ng-content> element at runtime.

2.

It creates _TabComponent_ components in the _TabsListComponent_ template when a _TabsListComponent_ is instantiated.

3.

It provides access from within the component class to any _TabComponent_ components that were content projected into the <ng-content> for this component.

4.

It restricts the allowed elements that can be put into a _TabsListComponent_ element to allow only _TabComponent_ elements.

Q 29 / 57

Angular

In order for Angular to process components in an application, where do the component types need to be registered?

1.

within a script tag in the index.html file

2.

in an NgModule decorator metadata tag named _components_

3.

No registration is needed simply include the component files in an app directory.

4.

in an NgModule decorator metadata property named _declarations_

Q 30 / 57

Angular

What is the purpose of the `fixture.detectChanges()` call in this unit test?

javascript TestBed.configureTestingModule({ declarations: [UserCardComponent], }); let fixture = TestBed.createComponent(UserCardComponent); fixture.detectChanges(); expect(fixture.nativeElement.querySelector('h1').textContent).toContain( fixture.componentInstance.title, );

1.

It tracks any potential Ul changes and will fail the unit test if any are made.

2.

It is used to ensure component template stability across multiple unit tests in the entire test suite.

3.

It forces Angular to perform change detection, which will render the _UserCardComponent_ before you can validate its template.

4.

It is used to log change-detection events to the console during unit test runs.

Q 31 / 57

Angular

What will the URL segment look like based on the following call to the `Router.navigate` method when goToUser is passed the value 15?

javascript export class ToolsComponent { constructor (private router: Router) { } goToUser (id: number) { this.router.navigate(['user', id]); } }

1.

/user/15

2.

/user?id=15

3.

/user:15

4.

/user;id=15

Q 32 / 57

Angular

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?

1.

A new instance of that service is created when the module is lazy loaded.

2.

Providing a service of the same type at a lazy-loaded module level is not allowed.

3.

If an instance of the service has not been created at the root level yet. it will create one there and then use it.

4.

A single instance of that service is always instantiated at root and is the only one ever used, including within lazy modules.

Q 33 / 57

Angular

What is the HostBinding decorator doing in this directive?

javascript @Directive({ selector: ' [appHighlight] ', }) export class HighlightDirective { @HostBinding('class.highlighted') highlight = true; }

1.

It is adding the CSS class named highlighted to any DOM element that has the appHighlight directive on it.

2.

HostBinding does not do anything on directives, only on components.

3.

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.

4.

It is creating an inline style on the host element with a CSS property named highlight set to true.

Q 34 / 57

Angular

In reactive forms, what Angular form class type is used on the native DOM <form> element to wire it up?

1.

`FormArray`

2.

`FormControl`

3.

`FormGroup`

4.

`all of these answers`

Q 35 / 57

Angular

Assuming the username FormControl has been configured with a minLength validator, how can you set up an error display in the following reactive forms markup for the username field?

html <form [formGroup]="form"› <input type="text" formControlName= "username"› ... </form> javascript <span *ngIf="username.minLength.invalid"› Username length is not valid </span> javascript <input type="text" formControlName="username" [showMinLength]="true"› javascript <span *ngIf="form.get('username').getError('minLength') as minLengthError"> Username must be at least {{ minLengthError.requiredLength }} characters. </span> javascript <input type="text" formControlName="username" #userName="ngModer"> <span *ngIf="userName.errors.minlength"› Username must be at least {{ userName.errors.minlength.requiredLength }} characters. </span>

1.

javascript <span *ngIf="username.minLength.invalid"› Username length is not valid </span>

2.

javascript <input type="text" formControlName="username" [showMinLength]="true"›

3.

javascript <span *ngIf="form.get('username').getError('minLength') as minLengthError"> Username must be at least {{ minLengthError.requiredLength }} characters. </span>

4.

javascript <input type="text" formControlName="username" #userName="ngModer"> <span *ngIf="userName.errors.minlength"› Username must be at least {{ userName.errors.minlength.requiredLength }} characters. </span>

Q 36 / 57

Angular

How does the emulated view encapsulation mode handle CSS for a component?

1.

It renders the CSS exactly how you wrote it without any changes.

2.

It makes use of shadow DOM markup and CSS.

3.

It creates unique attributes for DOM elements and scopes the CSS selectors you write to those attribute ids.

4.

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.

Q 37 / 57

Angular

With the following TestBed setup, what can be used to access the rendered DOM for the UserCardComponent?

javascript TestBed.configureTestingModule({ declarations: [UserCardComponent], }); let fixture = TestBed.createComponent(UserCardComponent);

1.

`fixture.componentTemplate`

2.

`fixture.getComponentHtml()`

3.

`fixture.nativeElement`

4.

`fixture.componentInstance.template `

Q 38 / 57

Angular

Given these two components, what will get rendered to the DOM based on the markup usage?

javascript @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> javascript <app-card> <h1>Data Card</hl> <app-bio> Been around for four years. </app-bio> </app-card> javascript <h1>Data Card</h1> <app-bio> Been around for four years. </app-bio> javascript <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> javascript <app-card> <h1>Data Card</hl> </app-card>

1.

javascript <app-card> <h1>Data Card</hl> <app-bio> Been around for four years. </app-bio> </app-card>

2.

javascript <h1>Data Card</h1> <app-bio> Been around for four years. </app-bio>

3.

javascript <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>

4.

javascript <app-card> <h1>Data Card</hl> </app-card>

Q 39 / 57

Angular

Given the app-title-card component in the code below, what DOM will the app-user-card component render?

javascript @Component({ selector: 'app-user-card', template: '<app-title-card></app-title-card><p>3enny Smith</p>' }) @Component({ selector: 'app-title-card', template: '<h1>User Data</hl>' }) // usage of user card component in parent component html <app-user-card></app-user-card> javascript <app-user-card> <app-title-card> <h1>User Data</h1> </app-title-card> <p>genny Smith</p> </app-user-card> javascript <h1>User Data</h1> <p>Jenny Smith<p> javascript <app-user-card> <app-title-card></app-title-card> </app-user-card> javascript <div app-user-card> <h1 app-title-card>User Data</h1> <p>Jenny Smith</p> </div>

1.

javascript <app-user-card> <app-title-card> <h1>User Data</h1> </app-title-card> <p>genny Smith</p> </app-user-card>

2.

javascript <h1>User Data</h1> <p>Jenny Smith<p>

3.

javascript <app-user-card> <app-title-card></app-title-card> </app-user-card>

4.

javascript <div app-user-card> <h1 app-title-card>User Data</h1> <p>Jenny Smith</p> </div>

Q 40 / 57

Angular

Pick the matching code for the custom provider registration that the @Inject () decorator is looking for:

javascript constructor(@Inject('Logger') private logger) { } javascript providers: [Logger]; javascript providers: [{ provide: 'Logger', useClass: Logger }]; javascript @Injectable({ providedln: 'root' }) javascript providers: [{ provide: 'Logger' }];

1.

javascript providers: [Logger];

2.

javascript providers: [{ provide: 'Logger', useClass: Logger }];

3.

javascript @Injectable({ providedln: 'root' })

4.

javascript providers: [{ provide: 'Logger' }];

Q 41 / 57

Angular

Which choice best describes the following usage of the HttpClient . get method in the getsettings class method?

javascript export class SettingsService { constructor(private httpClient: HttpClient) { } ... getSettings() { return this.httpClient.get < Settings > (this.settingsUrl) .pipe( retry(3) ); }}

1.

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.

2.

It will produce an error at runtime because the pipe method is not available off of the `Httpclient.get` call.

3.

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.

4.

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.

Q 42 / 57

Angular

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?

1.

Put the logic of that service method into the service constructor instead.

2.

Use a factory provider at the root AppModule level that depends on the service to call that service method.

3.

it is not possible to do it at application start; you can do it only at a component level.

4.

Instantiate an instance of the service at the global level (window scope) and then call that method.

Q 43 / 57

Angular

What statement best describes this usage of the TestBed?

javascript const spy = jasmine.createSpyObj('DataService', ['getUsersFromApi']); TestBed.configureTestingModule({ providers: [UserService, { provide: DataService, useValue: spy }], }); const userService = TestBed.get(UserService); `Although it will work when multiple providers in this configuration are asserted against in a single test.`

1.

The TestBed is required anytime you want to make use of a spy object in a unit test for an Angular provider.

2.

The TestBed is being used to test a component's view.

3.

The TestBed scaffolds an NgModule with two providers and handles any dependeny injection. If any Angular class requests the DataService in its constructor, the TestBed will inject spy in that constructor.

4.

The TestBed is configuring the test runner to tell it to only execute tests for the two providers listed in its providers array.

5.

undefined

Q 44 / 57

Angular

What is the primary difference between a component and a directive?

1.

A component uses a selector metadata property and a directive does not.

2.

A directive can be used for adding custom events to the DOM and a component cannot.

3.

A component has a template and a directive does not.

4.

A directive can target only native DOM elements.

Q 45 / 57

Angular

What could you add to this directive class to allow the truncate length to be set during directive usage in markup?

@Directive({ selector: '[appTruncate]' }) export class TruncateDirective { . . . } // example of desired usage: <p [appTruncate]="10">Some very long text here</p>

1.

`@Input() appTruncate: number;`

2.

`@Output() appTruncate;`

3.

`constructor(maxLength: number) { }`

4.

`Nothing. The directive selector cannot be used to pass in values to the directive.`

Q 46 / 57

Angular

How can you pass query parameters to this `HttpClient.get` request?

export class OrderService { constructor(private httpClient: HttpClient) { } getOrdersByYear(year: number): Observable<Order[]> { return this.httpClient.get<Order[]>(this.ordersUrl); } } const options = {params: new HttpParams().set('year', year) }; return this.httpClient.get<Order[]>(this.ordersUrl, options); angularjs getOrdersByYear(year: number): Observable<Order[]> { return this.httpClient.addParam('year', year).get<Order[]>(this.ordersUrl, year); }

1.

const options = {params: new HttpParams().set('year', year) }; return this.httpClient.get<Order[]>(this.ordersUrl, options);

2.

angularjs getOrdersByYear(year: number): Observable<Order[]> { return this.httpClient.addParam('year', year).get<Order[]>(this.ordersUrl, year); }

Q 47 / 57

Angular

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) {} ... }

1.

It is declaring that the `OrderHistoryComponent` will have its own version of a `DataService` and that it should never use any existing instances. The `DataService` would need to be instantiated within the class as a private field for this code to be complete and working.

2.

When Angular creates a new instance of the `OrderHistoryComponent`, the injector will provide an instance of a `DataService` class to the component constructor's first argument. The constructor's `dataService` parameter will be used to set a private instance field with the same name on the instance.

3.

It provides a way to do component testing only; the constructor has no usage in the actual run of the Angular application.

4.

It enables the custom element that the component targets to have a custom property named `dataService` that can be used to bind an existing `DataService` instance to.

Q 48 / 57

Angular

Finish this markup using the `ngIf` directive to implement an else case that will display the text "User is not active":

angular2html <div *ngIf="userIsActive; else inactive"> Currently active! </div> angular2html <div #inactive> User is not active. </div> angular2html <div *ngIf="inactive"> User is not active. </div> angular2html <ng-template #else="inactive"> <div>User is not active.</div> </ng-template> angular2html <ng-template #inactive> <div>User is not active.</div> </ng-template>

1.

angular2html <div #inactive> User is not active. </div>

2.

angular2html <div *ngIf="inactive"> User is not active. </div>

3.

angular2html <ng-template #else="inactive"> <div>User is not active.</div> </ng-template>

4.

angular2html <ng-template #inactive> <div>User is not active.</div> </ng-template>

Q 49 / 57

Angular

What is the correct syntax for a route definition to lazy load a feature module?

{ path: 'users', lazy: './users/users.module#UsersModule' } { path: 'users', loadChildren: () => import('./users/users.module').then(m => m.UserModule) } { path: 'users', loadChildren: './users/users.module#UsersModule' } { path: 'users', module: UsersModule }

1.

{ path: 'users', lazy: './users/users.module#UsersModule' }

2.

{ path: 'users', loadChildren: () => import('./users/users.module').then(m => m.UserModule) }

3.

{ path: 'users', loadChildren: './users/users.module#UsersModule' }

4.

{ path: 'users', module: UsersModule }

Q 50 / 57

Angular

Describe how the validation is set up and configured in this reactive forms example:

export class UserFormControl implements OnInit { ... ngOnInit() { this.form = this.formBuilder.group({ username: this.formBuilder.control('', [Validators.required, Validators.minLength(5), this.unique]), )}; } unique(control: FormControl) { return control.value !== 'admin' ? null: {notUnique: true}; } }

1.

The `FormControl` for `username` is getting configured to exclude three validators from the validators that it is allowed to use.

2.

The `FormControl` for `username` is getting configured to allow three possible validators to be used: `required, maxLength`, and a custom one named `unique`. To enable these `validators`, a validator directive would need to be put on the form fields in the markup.

3.

Validation cannot be set up this way in reactive forms.

4.

The `FormControl` for `username` is getting configured with three validators: the `required` and `minLength` validators that come from Angular, and a custom validator function named `unique` that checks for the value not equal to the string `admin`.

Q 51 / 57

Angular

What does the Injectable decorator do on this service class?

@Injectable({ providedIn: 'root' )} export class DataService { }

1.

It registers a provider for the service that is available only at the root module level, not to any children modules.

2.

It registers a provider for the service in the root application injector, making a single instance of it available throughout the application.

3.

It makes it so the service can be injected only in the bootstrapped component for the application.

4.

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.

Q 52 / 57

Angular

Describe the usage of this code

export interface AppSettings { title: string; version: number; } export const APP_SETTINGS = new Injection<AppSettings>('app.settings');

1.

The InjectionToken is adding an instance of the AppSettings to the root provider via the InjectionToken constructor call, making it automatically available to all NgModules, services and components throughout the Angular application without the need to inject it anywhere.

2.

The InjectionToken is used to create a provider token for a non-class dependency. An Object literal can be provider as a value for the APP_SETTINGS dependency provider type that can then be injected into components, services, etc ..

3.

The InjectionToken is used to create a dynamic decorator for the AppSettings that can be used on constructor parameters via an @AppSettings decorator.

4.

This code has an error since you cannot use a TypeScript interface for the generic type on the InjectionToken

Q 53 / 57

Angular

For the following template-driven forms example, what argument can be passed to the submit method in the click event to submit the data for the form?

<form #form="ngForm"> <input type="text" ngModel="firstName"> <input type="text" ngModel="lastName"> <button (click)="submit()">Save</button> </form>

1.

submit(form.value)

2.

submit($event)

3.

submit(ngForm.value)

4.

submit(FirstName, lastName)

Q 54 / 57

Angular

undefined

RouterModule.forRoot ( ... { preloadingStrategy: PreloadAllModules } )

1.

It enables the option to flag individual routes for preloading.

2.

It preloads all dependencies for routes, creating instances of services when the app first starts up

3.

It ensures all modules get built into a single app module bundle file.

4.

It configures the router to immediately load all routes that have a loadChildren property(routes that are typically loaded when requested)

Q 55 / 57

Angular

undefined

html <h1 [title]="userName">Current user is {{ userName }}</h1>

1.

title="userName"

2.

title="{{ userName }}"

3.

title="{{ 'userName' }}"

4.

The only way to do it is by using the square brackets.

Q 56 / 57

Angular

undefined

ts @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'); } }

1.

It is doing nothing, since the async pipe cannot be used in an `ngFor` statement.

2.

It is configuring the `ngFor` iteration to support multiple lists of users at the same time.

3.

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`.

4.

It is allowing all of the users in the `users` field to be rendered concurrently to the DOM.

Q 57 / 57