LinkedIn skill assessment answers and questions – Angular
Angolare is a popular framework for building dynamic web applications with JavaScript, TypeScript, eHTML. It offers many features and tools to simplify development, test, and deployment of web apps. If you want to learn Angular or improve your skills, you may want to take the LinkedIn skill assessment for Angular. This is a short online test that evaluates your knowledge of Angular concepts and best practices. Passing the test can boost your profile and showcase your expertise to potential employers and clients.
In questo articolo del blog, I will share with you some of the questions and answers from the LinkedIn skill assessment for Angular. These are based on my personal experience and research, but they may not reflect the exact questions you will encounter on the test. Perciò, use them as a reference and a learning resource, but not as a cheat sheet. You should always try to understand the logic behind the answers and not just memorize them. Per di qua, you will be able to apply your Angular skills in real-world scenarios and projects.
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 is 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
What method is used to wire up a FormControl to a native DOM input element in reactive forms?
Q2.- Add the string name given to the FormControl to an attribute named controls on the
<form>
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
paramMap
e il queryParamMap
sul ActivatedRoute
classe?
Q3. Qual è la differenza tra i file - 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.
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?
Q4.<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>
- Nessuna. The async pipe does not subscribe automatically.
- Nessuna. The template syntax is not correct.
- Tre. There is one for each async pipe.
- mentre altri sono piccoli cumuli di macerie legati insieme dalla gravità. The async pipe caches Observables by type internally.
How can you use the HttpClient to send a POST request to an endpoint from within an addOrder function in this OrderService?
Q5.export class OrderService {
constructor(private httpClient: HttpClient) {}
addOrder(order: Order) {
// Missing line
}
}
-
this.httpClient.url(this.orderUrl).post(order);
-
this.httpClient.send(this.orderUrl, order);
-
this.httpClient.post<Order>(this.orderUrl, order);
-
this.httpClient.post<Order>(this.orderUrl, order).subscribe();
Angular.io – Sending data to server
What is the RouterModule.forRoot method used for?
Q6.- 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.
Which DOM elements will this component metadata selector match on?
Q7.@Component({
selector: 'app-user-card',
. . .
})
- Any element with the attribute app-user-card, ad esempio
<div app-user-card></div>
. - The first instance of
<app-user-card></app-user-card>
. - All instances of
<app-user-card></app-user-card>
. - All instances of
<user-card></user-card>
.
Angular.io – Component Metadata
What is the correct template syntax for using the built-in ngFor structural directive to render out a list of productNames?
Q8.-
UN
<ul> <li [ngFor]="let productName of productNames">{{ productName }}</li> </ul>
-
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>
Angular.io- Structural Directives
What are the two-component decorator metadata properties used to set up CSS styles for a component?
D9.- viewEncapsulation and viewEncapsulationFiles.
- There is only one and it is the property named css.
- css and cssUrl.
- styles and styleUrls.
With the following component class, what template syntax would you use in the template to display the value of the title class field?
Q10.@Component({
selector: 'app-title-card',
template: '',
})
class TitleCardComponent {
title = 'User Data';
}
-
{{ 'title' }}
-
{{ title }}
-
[title]
- A class field cannot be displayed in a template via the template syntax.
Angular.io – String Interpolation or Text Interpolation
What is the purpose of the valueChanges method on a FormControl?
Dovrai almeno raggiungere.- It is used to configure what values are allowed for the control.
- 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.
- It returns a Boolean based on if the value of the control is different from the value with which it was initialized.
- 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.
Angular.io – Displaying a from control value
What directive is used to link an <a>
tag to routing?
D12. - routeTo
- routerLink
- routePath
- appLink
What is the Output decorator used for in this component class?
Q13.@Component({
selector: 'app-shopping-cart',
. . .
})
export class ShoppingCartComponent {
@Output() itemTotalChanged = new EventEmitter();
}
- It makes the
itemTotalChanged
class field public. - It provides a way to bind values to the
itemTotalChanged
class field, like so:<app-shopping-cart [itemTotalChanged]="newTotal"></app-shopping-cart>
. - It provides a way to bind events to the
itemTotalChanged
class field, like so:<app-shopping-cart (itemTotalChanged)="logNewTotal($event)"></app-shopping-cart>
. - It is simply a way to put a comment in front of a class field for documentation.
Angular.io – Sending data to parent component
What is the difference between these two markup examples for conditionally handling display?
Q14.<div *ngIf="isVisible">Active</div>
<div [hidden]="!isVisible">Active</div>
- Il
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.
- Il
ngIf
directive does not render the div in the DOM if the expression is false. Ilhidden
property usage hides the div content in the browser viewport, but the div is still in the DOM. - Il
ngIf
is valid, but the use of thehidden
property is wrong and will throw an error.
How can you disable the submit button when the form has errors in this template-driven forms example?
Q15.<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>
-
UN
<button (click)="submit(userForm.value)" disable="userForm.invalid">Save</button>
-
B
<button (click)="submit(userForm.value)" [disabled]="userForm.invalid">Save</button>
-
C
<button (click)="submit(userForm.value)" [ngForm.disabled]="userForm.valid">Save</button>
-
D
<button (click)="submit(userForm.value)" *ngIf="userForm.valid">Save</button>
Angular.io – Submit the form with ngSubmit
You want to see what files would be generated by creating a new contact-card component. Which command would you use?
Q16.- ng generate component contact-card –dry-run
- ng generate component contact-card –no-files
- ng generate component component –dry
- ng generate component –exclude
Angular.io – ng generate options
Based on the following component, what template syntax would you use to bind the TitleCardComponent’s titleText field to the h1 element title property?
Q17.@Component({
selector: 'app-title-card',
template: '<h1 title="User Data"> {{titleText}}</h1>',
})
export class TitleCardComponent {
titleText = 'User Data';
}
-
<h1 data-title="titleText">{{ titleText }}</h1>
-
<h1 title="titleText">{{ titleText }}</h1>
-
<h1 [title]="titleText">{{ titleText }}</h1>
-
<h1 titleText>{{ titleText }}</h1>
Angular.io – String Interpolation
What are Angular lifecycle hooks?
D18.- loggers for tracking the health of an Angular app
- providers that can be used to track the instances of components
- built-in pipes that can be used in templates for DOM events
- 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
Pick the best description for this template syntax code:
D19.<span>Boss: {{job?.bossName}} </span>
- Il ? 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. Il ? is not valid here.
- It is diplaying the job value if it has one; otherwise it is displaying the bossName.
How would you configure a route definition for a UserDetailComponent that supports the URL path user/23 (dove 23 represents the id of the requested user)?
Q20.-
{ path: 'user/:id', component: UserDetailComponent }
-
{ url: 'user/:id', routedComponent: UserDetailComponent }
-
{ routedPath: 'user/:id', component: UserDetailComponent }
-
{ destination: new UserDetailComponent(), route: 'user/:id' }
CodeCraft – Parameterised Routes
What are the HostListener decorators and the HostBinding decorator doing in this directive?
D21.@Directive({
selector: '[appCallout]',
})
export class CalloutDirective {
@HostBinding('style.font-weight') fontWeight = 'normal';
@HostListener('mouseenter')
onMouseEnter() {
this.fontWeight = 'bold';
}
@HostListener('mouseleave')
onMouseLeave() {
this.fontWeight = 'normal';
}
}
- Stanno impostando il campo CalloutDirective.fontWeight in base al fatto che il mouse si trovi o meno sull'elemento DOM. HostListener imposta quindi la proprietà CSS font-weight sul valore fontWeight.
- Stanno impostando la direttiva per verificare l'elemento DOM su cui si trova. Se sono state aggiunte associazioni di eventi per l'immissione e l'uscita del mouse, utilizzerà questo codice. Altrimenti, non succederà nulla.
- Si tratta di un utilizzo errato di HostListener e HostBinding. I decoratori HostListener e HostBinding non fanno nulla sulle direttive; funzionano solo se utilizzati sui componenti.
- Se l'elemento DOM su cui è posizionata questa direttiva ha la proprietà CSS font-weight impostata su di esso, verranno generati gli eventi mouseenter e mouseleave.
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?
Q22.<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.
What is the value type that will be stored in the headerText template reference variable in this markup?
Q23.<h1 #headerText>User List</h1>
- an Angular ElementRef, a wrapper around a native element
- the inner text of the
<h1>
elemento - a header component class
- the native DOM element type of HTMLHeadingElement
Pluralsight – Template reference variable
of the resulting code logic based on these two provider configurations?
Q24. Qual è la differenza, Questi casi si distinguono per l'insorgenza improvvisa di segni clinici e il conseguente rapido miglioramento con scarso,[{ provide: FormattedLogger, useClass: Logger }][{ provide: FormattedLogger, useExisting: Logger }];
- 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 cannot 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.
What is the purpose of the data property (seen in the example below) in a route configuration?
Q25. {
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
- 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.
How does the built-in ngIf
structural directive change the rendered DOM based on this template syntax?
Q26. @Component({
selector: 'app-product',
template: '<div *ngIf="product">{{ product.name }}</div>',
})
export class ProductComponent {
@Input() product;
}
- Il
<div>
acts as a placeholder. If the product class field is “truthy,” il<div>
will get replaced by just theproduct.name
valore; spostali in tutte le direzioni per vedere se si sposta, then nothing will be rendered. - Il
<div>
will always be rendered, and if the product field is “truthy,” il<div>
element will contain theproduct.name
valore; altrimenti, it will render the<div>
element with no value in it. - It produces an error since ngIf is not a built-in structural directive.
- If the product class field is “truthy,” then the rendered DOM will include the
<div>
with the value of theproduct.name
campo. If it is not “truthy,’ the rendered DOM will not contain the<div>
elemento.
What does this code accomplish?
D27.@NgModule({
declarations: [AppComponent],
imports: [BrowserModule],
bootstrap: [AppComponent],
})
export class AppModule {}
platformBrowserDynamic().bootstrapModule(AppModule);
- It executes a unit test for an NgModule.
- 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.
- It declares an Angular module named AppModule and makes it available for lazy loading throughout the application.
- 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.
Angular.io – The basic NgModule
Which choice best describes what the resolve proprietà fa in questa configurazione di percorso?
D28.{
path: ':id',
component: UserComponent,
resolve: {
user: UserResolverService
}
}
- Prima di caricare il Componente utente, il router si iscriverà a Osservabile restituito da a resolve metodo nel ServizioResolverUtente. Questa tecnica può essere utilizzata per ottenere dati precaricati per a itinerario.
- Dopo il itinerario ha finito di risolversi, e il componente viene caricato e sottoposto a rendering, il ServizioResolverUtente avrà un metodo denominato utente eseguire che ripulirà tutte le connessioni dati aperte.
- C'è un errore. Il nome corretto della proprietà è onResolve.
- Il Componente utente avrà un parametro nel suo costruttore per utente, e il router gestirà l'inserimento di un valore per quello da una chiamata ad a utente metodo nel ServizioResolverUtente.
D29. Qual è lo scopo del decoratore ContentChildren in questa classe componente?
@Component({
. . .
template: '<ng-content></ng-content>'
})
export class TabsListComponent {
@ContentChildren(TabComponent) tabs;
}
- Se presente SchedeComponente gli elementi vengono aggiunti al ComponenteElencoSchede modello, verranno inseriti nel
<ng-content>
elemento in fase di esecuzione. - Crea SchedaComponente componenti in ComponenteElencoSchede modello quando a ComponenteElencoSchede è istanziato.
- It provides access from within the component class to any SchedaComponente components that were content projected into the
<ng-content>
for this component. - It restricts the allowed elements that can be put into a ComponenteElencoSchede element to allow only SchedaComponente elementi.
In order for Angular to process components in an application, where do the component types need to be registered?
Q30.- within a script tag in the index.html file
- in a NgModule decorator metadata tag named componenti
- No registration is needed simply include the component files in an app directory.
- in a NgModule decorator metadata property named dichiarazioni
fixture.detectChanges()
call in this unit test?
Q31. Qual è lo scopo del TestBed.configureTestingModule({
declarations: [UserCardComponent],
});
let fixture = TestBed.createComponent(UserCardComponent);
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.
What will the URL segment look like based on the following call to the Router.navigate
method when goToUser is passed the value 15?
Q32. export class ToolsComponent {
constructor(private router: Router) {}
goToUser(id: number) {
this.router.navigate(['user', id]);
}
}
- /user/15
- /utente?id=15
- /utente:15
- /utente;id=15
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?
____ base.- 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. ne creerà uno lì e poi lo utilizzerà.
- Una singola istanza di quel servizio viene sempre istanziata alla radice ed è l'unica mai utilizzata, anche all'interno dei moduli pigri.
Q34. Cosa fa il decoratore HostBinding in questa direttiva?
@Directive({
selector: ' [appHighlight] ',
})
export class HighlightDirective {
@HostBinding('class.highlighted') highlight = true;
}
- Sta aggiungendo la classe CSS denominata evidenziata a qualsiasi elemento DOM che contenga la direttiva appHighlight.
- HostBinding non fa nulla sulle direttive, solo sui componenti.
- Specifica che se l'elemento host ottiene la classe evidenziata aggiunta al suo attributo class, quindi l'evidenziazione del campo della classe direttiva verrà impostata su true; e se non viene aggiunto all'host verrà impostato su false.
- Sta creando uno stile in linea sull'elemento host con una proprietà CSS denominata highlight impostata su true.
what Angular form class type is used on the native DOM <form>
element to wire it up?
Ultimo strato. Nelle forme reattive, -
FormArray
-
FormControl
-
FormGroup
-
all of these answers
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?
Q36.<form [formGroup]="form">
<input type="text" formControlName="username" />
...
</form>
-
UN
<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 minLengthError"> Username must be at least {{ minLengthError.requiredLength }} characters. </span>
-
D
<input type="text" formControlName="username" #userName="ngModel" /> <span *ngIf="userName.errors.minlength"> Username must be at least {{ userName.errors.minlength.requiredLength }} characters. </span>
How does the emulated view encapsulation mode handle CSS for a component?
Q37.- 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 in the template.
With the following TestBed setup, what can be used to access the rendered DOM for the UserCardComponent?
Q38.TestBed.configureTestingModule({
declarations: [UserCardComponent],
});
let fixture = TestBed.createComponent(UserCardComponent);
-
fixture.componentTemplate
-
fixture.getComponentHtml()
-
fixture.nativeElement
-
fixture.componentInstance.template
Given these two components, what will get rendered to the DOM based on the markup usage?
Q39.@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>
-
UN
<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>
Given the app-title-card component in the code below, what DOM will the app-user-card component render?
Q40.@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>'
})
// usage of user card component in parent component html
<app-user-card></app-user-card>
-
UN
<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> <p></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>
Pick the matching code for the custom provider registration that the @Inject () decorator is looking for:
Q41.constructor(@Inject('Logger') private logger) { }
-
UN
providers: [Logger];
-
B
providers: [{ provide: 'Logger', useClass: Logger }];
-
C
@Injectable({ providedln: 'root' })
-
D
providers: [{ provide: 'Logger' }];
Which choice best describes the following usage of the HttpClient.get method in the getsettings class method?
Q42.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
chiamata. - Ogni singola chiamata al metodo getSettings comporterà che Httpclient effettui tre richieste di get totali a settingsUrl, il che non è l'ideale perché ci saranno sempre due chiamate extra che non saranno necessarie. L'operatore retry non deve essere utilizzato in questo modo.
- Quando viene sottoscritto il risultato del metodo getSettings, verrà effettuata la chiamata HTTP GET; se fallisce, verrà ritentato fino a tre volte prima di arrendersi e restituire un errore.
Q43. Quando un servizio richiede alcune impostazioni per inizializzare il suo stato predefinito tramite un metodo, come puoi assicurarti che detto metodo venga invocato prima che il servizio venga iniettato ovunque?
- Inserisci invece la logica di quel metodo di servizio nel costruttore del servizio.
- Utilizza un provider di fabbrica al livello AppModule root che dipende dal servizio per chiamare quel metodo di servizio.
- Non è possibile farlo all'avvio dell'applicazione; puoi farlo solo a livello di componente.
- Istanziare un'istanza del servizio a livello globale (ambito della finestra) e quindi chiamare quel metodo.
Q44. Quale affermazione descrive meglio questo utilizzo del TestBed?
const spy = jasmine.createSpyObj('DataService', ['getUsersFromApi']);
TestBed.configureTestingModule({
providers: [UserService, { provide: DataService, useValue: spy }],
});
const userService = TestBed.get(UserService);
- Il TestBed è richiesto ogni volta che desideri utilizzare un oggetto spia in un test unitario per un provider Angular.
- Il TestBed viene utilizzato per testare la vista di un componente.
- Il TestBed supporta un NgModule con due provider e gestisce qualsiasi inserimento di dipendenze. Se una classe Angular richiede DataService nel suo costruttore, il TestBed inietterà la spia in quel costruttore.
- 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.
What is the primary difference between a component and a directive?
Q45.- A component uses a selector metadata property and a directive does not.
- A directive can be used for adding custom events to the DOM and a component cannot.
- A component has a template and a directive does not.
- A directive can target only native DOM elements.
What could you add to this directive class to allow the truncate length to be set during directive usage in markup?
Q46.@Directive({
selector: '[appTruncate]'
})
export class TruncateDirective {
. . .
}
// example of desired usage:
<p [appTruncate]="10">Some very long text here</p>
-
@Input() appTruncate: number;
-
@Output() appTruncate;
-
constructor(maxLength: number) { }
-
Nothing. The directive selector cannot be used to pass in values to the directive.
How can you pass query parameters to this HttpClient.get
request?
Q47. export class OrderService {
constructor(private httpClient: HttpClient) {}
getOrdersByYear(year: number): Observable<Order[]> {
return this.httpClient.get<Order[]>(this.ordersUrl);
}
}
-
UN
return this.httpClient.get<Order[]>(this.ordersUrl, {'year': year})
-
B
return this.httpClient.get<Order[]>(this.ordersUrl, year)
-
C
const options = { params: new HttpParams().set('year', year) }; return this.httpClient.get<Order[]>(this.ordersUrl, options);
-
D
getOrdersByYear(year: number): Observable<Order[]> { return this.httpClient.addParam('year', year).get<Order[]>(this.ordersUrl, year); }
Assuming the DataService
has been registered in the providers for the application, which answer best describes what happens based on this component’s constructor?
D48. @Component({
...
})
export class OrderHistoryComponent {
constructor(private dataService: DataService) {}
...
}
- It declares that the
OrderHistoryComponent
will have its own version of aDataService
and that it should never use any existing instances. IlDataService
would need to be instantiated within the class as a private field for this code to be complete and working. - When Angular creates a new instance of the
OrderHistoryComponent
, the injector will provide an instance of aDataService
class to the component constructor’s first argument. The constructor’sdataService
parameter will be used to set a private instance field with the same name on the instance. - It provides a way to do component testing only; the constructor has no usage in the actual run of the Angular application.
- It enables the custom element that the component targets to have a custom property named
dataService
that can be used to bind an existingDataService
instance to.
Finish this markup using the ngIf
directive to implement an else case that will display the text “User is not active”:
Q49. <div *ngIf="userIsActive; else inactive">Currently active!</div>
-
UN
<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>
What is the correct syntax for a route definition to lazy load a feature module?
Q50.-
UN
{ path: 'users', lazy: './users/users.module#UsersModule' }
-
B
{ path: 'users', loadChildren: () => import('./users/users.module').then(m => m.UserModule) }
-
C
{ path: 'users', loadChildren: './users/users.module#UsersModule' }
-
D
{ path: 'users', module: UsersModule }
Angular.io – Lazy Loading Modules
Describe how the validation is set up and configured in this reactive forms example:
Q51.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};
}
}
- Il
FormControl
perusername
is getting configured to exclude three validators from the validators that it is allowed to use. - Il
FormControl
perusername
is getting configured to allow three possible validators to be used:required, maxLength
, and a custom one namedunique
. To enable thesevalidators
, a validator directive would need to be put on the form fields in the markup. - Validation cannot be set up this way in reactive forms.
- Il
FormControl
perusername
is getting configured with three validators: ilrequired
eminLength
validators that come from Angular, and a custom validator function namedunique
that checks for the value not equal to the stringadmin
.
What does the Injectable decorator do on this service class?
Q52.@Injectable({
providedIn: 'root'
)}
export class DataService { }
- 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.
Describe the usage of this code
Q53.export interface AppSettings {
title: string;
version: number;
}
export const APP_SETTINGS = new InjectionToken<AppSettings>('app.settings');
- The InjectionToken adds an instance of the AppSettings to the root provider via the InjectionToken constructor call, making it automatically available to all NgModules, servizi e componenti in tutta l'applicazione Angular senza la necessità di inserirli ovunque.
- InjectionToken viene utilizzato per creare un token provider per una dipendenza non di classe. Un valore letterale oggetto può essere fornito come valore per il tipo di provider di dipendenze APP_SETTINGS che può quindi essere inserito nei componenti, Servizi, eccetera ..
- InjectionToken viene utilizzato per creare un decoratore dinamico per AppSettings che può essere utilizzato sui parametri del costruttore tramite un decoratore @AppSettings.
- Questo codice presenta un errore poiché non è possibile utilizzare un'interfaccia TypeScript per il tipo generico su InjectionToken
Q54. Per il seguente esempio di moduli basati su modello, quale argomento può essere passato al metodo di invio nell'evento clic per inviare i dati per il modulo?
<form #form="ngForm">
<input type="text" ngModel="firstName" /> <input type="text" ngModel="lastName" />
<button (click)="submit()">Save</button>
</form>
- invia(forma.valore)
- invia($evento)
- invia(ngForm.valore)
- invia(Nome di battesimo, cognome)
prelodingStrategy
property configuration in this router code?
Q55. Qual è lo scopo del RouterModule.forRoot(
...{
preloadingStrategy: PreloadAllModules,
},
);
- It enables the option to flag individual routes for preloading.
- It preloads all dependencies for routes, creating instances of services when the app first starts up
- It ensures all modules get built into a single app module bundle file.
- It configures the router to immediately load all routes that have a loadChildren property(routes that are typically loaded when requested)
Riferimenti:
- Angular Router, PreloadAllModules
- Route preloading in Angular
- Preloading strategy
- Custom preloading strategy
- Preloading strategy, save loading time
What is an alternative way to write this markup to bind the value of the class field userName
al h1
element title property?
Q56. <h1 [title]="userName">Current user is {{ userName }}</h1>
-
title="userName"
-
title="{{ userName }}"
-
title="{{ 'userName' }}"
- The only way to do it is by using the square brackets.
async
pipe doing in this example?
Q57. Quale è @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
dichiarazione. - 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 thengFor
. - It is allowing all of the users in the
users
field to be rendered concurrently to the DOM.
How would you make use of this directive in markup based on its selector value
D58.@Directive({ selector: '[appTruncate]'
})
export class TruncateDirective{ . . .
}
-
html <p data-directive="appTruncate">Some long text </p>
-
html <p appTruncate>Some long text</p>
-
html <p app-truncate>Some long text</p>
-
html <app-truncate>Some long text</app-truncate>
What lifecycle hook can be used on a component to monitor all changes to @Input values on that component?
Q59.- ngOnInit
- ngChanges
- ngAfterInputChange
- ngOnChanges
How to detect when an @Input() value changes in Angular?
What would be an example template syntax usage of this custom pipe?
Q60.@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;
}
}
-
{{ 'some long text' | truncate:10 }}
-
{{ 'some long text' | truncate: 10, true }}
-
{{ 'some long text' | truncate }}
- tutte queste risposte
[How do I call an Angular 2 pipe with multiple arguments?] (https://stackoverflow.com/questions/36816788/how-do-i-call-an-angular-2-pipe-with-multiple-arguments)
Q61. Quale comando CLI di Angular eseguiresti per generare un UsersComponent e aggiungerlo a SharedModule (nel file shared.module.ts nella tua applicazione)?
- ng generate component –nuovoModulo=condiviso
- di generare utenti dei componenti –modulo=condiviso
- di generare utenti dei componenti –condivisa
- ng generate component –aggiungi=condiviso
Q62. Come puoi riscrivere questo markup in modo che il contenitore div non sia necessario nel rendering DOM finale
<div *ngIf="location">
<h1>{{ location.name }}</h1>
<p>{{ location.description }}</p>
</div>
-
UN
<div *ngIf="location"> <h1>{{ location.name }}</h1> <p>{{ location.description }}</p> {{ endNgIf }} </div>
-
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>
Describe the usage of this code:
D63.export interface AppSettings {
title: string;
version: number;
}
- Questo codice è un errore poiché non è possibile utilizzare un'interfaccia TypeScript per il tipo generico su InjectionToken.
- InjectionToken viene utilizzato per creare un token provider per una dipendenza non di classe. È possibile fornire un oggetto letterale come valore per il tipo di provider di dipendenze APP_SETTINGS che può quindi essere inserito nei componenti, Servizi, eccetera.
- InjectionToken sta aggiungendo un'istanza di AppSettings al provider root tramite la chiamata del costruttore InjectionToken, rendendolo automaticamente disponibile per tutti gli NgModule, Servizi, 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.
What Angular utilities, Questi casi si distinguono per l'insorgenza improvvisa di segni clinici e il conseguente rapido miglioramento con scarso, are required to unit test a service with no constructor dependencies?
Q64.- By.css() helper method is needed
- A text fixture is required to run the service for the unit test.
- Nessuna. A service can be instantiated and unit tested on its own.
- The TestBed class is needed to instantiate the service.
Angular unit tests – recheck answers
What is the difference between the CanActivate and the CanLoad route guards?
Q65.- 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.
What is the outlet property used for in this router definition object?
Q66.{ path: 'document', component: DocumentComponent, outlet: 'document-box'
}
- it will locate all instancess of
<document-box>
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
<document-box>
element in addition ot being routed to. - It us used to target a
<router-outlet>
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
In this template syntax, every time the items property is changed (added to, rimosso da, eccetera.), 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?
Q67.<div *ngFor="let item of items">{{ item.id }} - {{ item.name }}</div>
-
*ngFor="let item of items; let uniqueItem"
-
*ngFor="let item of items.distinct()"
-
*ngFor="let item of items: let i = index"
-
*ngFor="let item of items; trackBy: trackById"
StackOverflow – How to use trackBy
con ngFor
What does this Angular CLI command do?
Q68.ng build --configuration=production --progress=false
- It builds the Angular application, setting the build configuration to the “produzione” target specified in the angular.json file, and logs progress output to the console.
- It builds the Angular application, setting the build configuration to the “produzione” target specified in the angular.json file, and watching files for changes.
- It builds the Angular application, setting the build configuration to the “produzione” target specified in the angular.json file, and disables watching files for changes.
- It builds the Angular application, setting the build configuration to the “produzione” target specified in the angular.json file, and prevents progress output to the console.
Angular documentation – ng build
Service classes can be registered as providers via which decorators?
Q69.- @Injectable, @NgModule, @Component, and @Directive.
- @Injectable only.
- @Injectable and @NgModule only.
- @Service and @NgModule only.
What is the Input decorator used for in this component class?
Q70.@Component({ selector:'app-product-name', ...
})
export class ProductNameComponent { @Input() productName: string
}
- It is used simply to put a comment in front of a class field for documentation.
- It provides a way to bind values to the productName field by using the component selector.
- It autogenerates an
html <input type='text' id='productName'>
Dom element in the component template. - It provides a way to bind values to the productName instance field,just like native DOM element property bindings. Angular documentation –
Input()
Which route guard can be used to mediate navigation to a route?
Q71.- tutte queste risposte.
- CanDeactivate.
- CanLoad
- CanActivate. Angular documentation –
Input()
How can you configure the injector to use an existing object for a token instead of having it instantiate a class instance?
Ultimo strato.- Utilizzare il
useValue
provider configuration and set that equal to an existing object or an object literal. - It is not possible. Providers can be configured only with class types.
- Simply add the object instance or literal to the provider’s array.
- Make use of the
asValue
provider configuration property, setting it to true.
Configuring dependency providers
Based on this route definition, what can be injected into UserDetailComponent constructor to get ahold of the id route parameter?
Q73.{path: 'user/:id', component: UserDetailComponent }
- ActivatedRoute
- CurrentRoute
- UrlPath
- @Inject(‘id’)
With the following reactive form markup, what would you add to wire up a call to an onSubmit class method?
Un impianto di processo è più vulnerabile durante le operazioni di arresto e avviamento.<form [formGroup]="form">
<input type="text" formControlName="username" />
<button type="submit" [disabled]="form. invalid">Submit</button>
</form>
- neither of these answers
- Inserisci (clic)=”onSubmit()” al
<button>
elemento. - Inserisci (ngSubmit )=”onSubmit ()” al
<form>
elemento. - both of these answers
What is the expected DOM code for this usage of the ngClass attribute directive when isActive is true?
Q75.<div [ngClass]="{ ‘active-item': isActive }">Item One</div>
-
<div active-item>Item One</div>
-
<div class="active-item">Item One</div>
-
<div class="is-active">Item One</div>
-
<div class="active-item isActive">Item One</div>
Which answer best explains the usage of ngModel in this template code?
Q76.<input [(ngModel)]="user.name" />
- It is conditionally displaying the input element if the user.name property has a value.
- It is the two-way data binding syntax. The input element value property will be bound to the user.name property, and the value change event for the form element will update the user.name property value.
- There is a typo in the code. It should have only the square brackets.
- It is binding the value of the user.name property to the input element’s val property to set its initial value.
What method is used to wire up a FormControl to a native DOM input element in reactive forms?
Q77.- Use the string name given to the FormControl as the value for the DOM element id attribute.
- Use the formControlName directive and set the value equal to the string name given to the FormControl.
- Add the string name given to the FormControl to an attribute named controls on the
<form>
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.
What other template syntax (replacing the ngClass directive) può essere utilizzato per aggiungere o rimuovere i nomi delle classi CSS in questo markup?
D78.<span [ngClass]="{ 'active': isActive, 'can-toggle': canToggle }"> Employed </span>
-
UN
<span class="{{ isActive ? 'is-active' : '' }} {{ canToggle ? 'can-toggle' : '' }}"> Employed </span>
-
B
<span [class.active]="isActive" [class.can-toggle]="canToggle"> Employed </span>
-
C
<span [styles.class.active]="isActive" [styles.class.can-toggle]="canToggle"> Employed </span>
-
D
<span [css.class.active]="isActive" [css.class.can-toggle]="canToggle"> Employed </span>
D79. In questo esempio di decoratore di direttive, qual è lo scopo della proprietà multi nell'oggetto provider letterale?
@Directive({
selector: '[customValidator]',
providers: [
{
provide: NG_VALIDATORS,
useExisting: CustomValidatorDirective,
multi: true,
},
],
})
export class CustomValidatorDirective implements Validator {}
- Indica che CustomValidatorDirective può essere utilizzato su più tipi di elementi del modulo.
- Consente di istanziare più istanze di CustomValidatorDirective. Senza multiplo, CustomValidatorDirective sarebbe un singleton per l'intera app.
- Permette la registrazione di diversi provider per il singolo token NG_VALIDATORS. In questo caso, sta aggiungendo CustomValidatorDirective all'elenco dei validatori di moduli disponibili.
- Indica che saranno presenti più classi che gestiranno l'implementazione logica per il validatore personalizzato.
Which Angular CLI command would you use to run your unit tests in a process that reruns your test suite on file changes?
Q80.- ng test –single-run=false
- ng test –watch-files
- ng test –progress
- ng test
What is the most common use for the ngOnDestory lifecle hook?
Q81.- Remove dome elements from the components’s view
- All of these answers
- Delete any injected services the
- Unsubscribe from observables and detach
What NgModule decorator metadata property is leverage to allow other ….?
Q82.- pubblico
- Ciò riflette il ruolo del rapporto nella risposta del Dipartimento dell'Energia ad a
- Shared
- dichiarazioni
What is the difference between the CanActivate and the CanLoad rout guards?
Q83.- CanLoad Prevents an entire NGModule from being delivered and loaded. CanActivate stops routing to a component in that NgModule , but the module is still loaded.
- CanActivate and CanLoad do the exact same thing.
- 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
With the following component class, what template syntax would you use in the template to display the result of calling the currentYear class function?
Q84.@Component({
selector: 'app-date-card',
template: '',
})
export class DateCardComponent {
currentYear() {
return new Date().getFullYear();
}
}
-
{{ currentYear() }}
-
{{ component.currentYear() }}
-
{{ currentYear }}
- Class functions cannot be called from template syntax.
Lascia un commento
Devi accesso o Registrati per aggiungere un nuovo commento .