Angular test question 3 (105 included) Flashcards

Style, state, animation, type, AOT, JIT

1
Q

What are active router links?

A

RouterLinkActive is a directive that toggles css classes for active RouterLink bindings based on the current RouterState. i.e, The Router will add CSS classes when this link is active and remove when the link is inactive. For example, you can add them to RouterLinks as below.

<h1>Angular Router</h1>

<nav>
<a>List of todos</a>
<a>Completed todos</a>
</nav>

<router-outlet></router-outlet>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is router state?

A

RouterState is a tree of activated routes. Every node in this tree knows about the “consumed” URL segments, the extracted parameters, and the resolved data. You can access the current RouterState from anywhere in the application using the Router service and the routerState property.

@Component({templateUrl:’template.html’})
class MyComponent {
constructor(router: Router) {
const state: RouterState = router.routerState;
const root: ActivatedRoute = state.root;
const child = root.firstChild;
const id: Observable<string> = child.params.map(p => p.id);
//...
}
}</string>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What are router events?

A

During each navigation, the Router emits navigation events through the Router.events property allowing you to track the lifecycle of the route.

The sequence of router events is as below,

NavigationStart,
RouteConfigLoadStart,
RouteConfigLoadEnd,
RoutesRecognized,
GuardsCheckStart,
ChildActivationStart,
ActivationStart,
GuardsCheckEnd,
ResolveStart,
ResolveEnd,
ActivationEnd
ChildActivationEnd
NavigationEnd,
NavigationCancel,
NavigationError
Scroll

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is activated route?

A

ActivatedRoute contains the information about a route associated with a component loaded in an outlet. It can also be used to traverse the router state tree. The ActivatedRoute will be injected as a router service to access the information. In the below example, you can access route path and parameters,

@Component({…})
class MyComponent {
constructor(route: ActivatedRoute) {
const id: Observable<string> = route.params.pipe(map(p => p.id));
const url: Observable<string> = route.url.pipe(map(segments => segments.join('')));
// route.data includes both `data` and `resolve`
const user = route.data.pipe(map(d => d.user));
}
}</string></string>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How do you define routes?

A

How do you define routes?

A router must be configured with a list of route definitions. You configures the router with routes via the RouterModule.forRoot() method, and adds the result to the AppModule’s imports array.

const appRoutes: Routes = [
{ path: ‘todo/:id’, component: TodoDetailComponent },
{
path: ‘todos’,
component: TodosListComponent,
data: { title: ‘Todos List’ }
},
{ path: ‘’,
redirectTo: ‘/todos’,
pathMatch: ‘full’
},
{ path: ‘**’, component: PageNotFoundComponent }
];

@NgModule({
imports: [
RouterModule.forRoot(
appRoutes,
{ enableTracing: true } // <– debugging purposes only
)
// other imports here
],

})
export class AppModule { }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is the purpose of Wildcard route?

A

If the URL doesn’t match any predefined routes then it causes the router to throw an error and crash the app. In this case, you can use wildcard route. A wildcard route has a path consisting of two asterisks to match every URL.

For example, you can define PageNotFoundComponent for wildcard route as below

{ path: ‘**’, component: PageNotFoundComponent }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Do I need a Routing Module always?

A

No, the Routing Module is a design choice. You can skip routing Module (for example, AppRoutingModule) when the configuration is simple and merge the routing configuration directly into the companion module (for example, AppModule). But it is recommended when the configuration is complex and includes specialized guard and resolver services.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What are different types of compilation in Angular?

A

Angular offers two ways to compile your application,
Just-in-Time (JIT)
Ahead-of-Time (AOT)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is JIT?

A

Just-in-Time (JIT) is a type of compilation that compiles your app in the browser at runtime. JIT compilation was the default until Angular 8, now default is AOT. When you run the ng build (build only) or ng serve (build and serve locally) CLI commands, the type of compilation (JIT or AOT) depends on the value of the aot property in your build configuration specified in angular.json. By default, aot is set to true.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is AOT?

A

Ahead-of-Time (AOT) is a type of compilation that compiles your app at build time. This is the default starting in Angular 9. When you run the ng build (build only) or ng serve (build and serve locally) CLI commands, the type of compilation (JIT or AOT) depends on the value of the aot property in your build configuration specified in angular.json. By default, aot is set to true.

ng build
ng serve

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Why do we need compilation process?

A

The Angular components and templates cannot be understood by the browser directly. Due to that Angular applications require a compilation process before they can run in a browser. For example, In AOT compilation, both Angular HTML and TypeScript code converted into efficient JavaScript code during the build phase before browser runs it.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What are the advantages with AOT?

A

Faster rendering: The browser downloads a pre-compiled version of the application. So it can render the application immediately without compiling the app.
Fewer asynchronous requests: It inlines external HTML templates and CSS style sheets within the application javascript which eliminates separate ajax requests.
Smaller Angular framework download size: Doesn’t require downloading the Angular compiler. Hence it dramatically reduces the application payload.
Detect template errors earlier: Detects and reports template binding errors during the build step itself
Better security: It compiles HTML templates and components into JavaScript. So there won’t be any injection attacks.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What are the ways to control AOT compilation?

A

You can control your app compilation in two ways,
By providing template compiler options in the tsconfig.json file
By configuring Angular metadata with decorators

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What are the restrictions of metadata?

A

In Angular, You must write metadata with the following general constraints,
Write expression syntax with in the supported range of javascript features
The compiler can only reference symbols which are exported
Only call the functions supported by the compiler
Decorated and data-bound class members must be public.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What are the three phases of AOT?

A

The AOT compiler works in three phases,
Code Analysis: The compiler records a representation of the source
Code generation: It handles the interpretation as well as places restrictions on what it interprets.
Validation: In this phase, the Angular template compiler uses the TypeScript compiler to validate the binding expressions in templates.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Can I use arrow functions in AOT?

A

No, Arrow functions or lambda functions can’t be used to assign values to the decorator properties. For example, the following snippet is invalid:

@Component({
providers: [{
provide: MyService, useFactory: () => getService()
}]
})
To fix this, it has to be changed as following exported function:

function getService(){
return new MyService();
}

@Component({
providers: [{
provide: MyService, useFactory: getService
}]
})
If you still use arrow function, it generates an error node in place of the function. When the compiler later interprets this node, it reports an error to turn the arrow function into an exported function. Note: From Angular5 onwards, the compiler automatically performs this rewriting while emitting the .js file.

17
Q

What is folding?

A

The compiler can only resolve references to exported symbols in the metadata. Where as some of the non-exported members are folded while generating the code. i.e Folding is a process in which the collector evaluate an expression during collection and record the result in the .metadata.json instead of the original expression. For example, the compiler couldn’t refer selector reference because it is not exported

let selector = ‘app-root’;
@Component({
selector: selector
})
Will be folded into inline selector

@Component({
selector: ‘app-root’
})
Remember that the compiler can’t fold everything. For example, spread operator on arrays, objects created using new keywords and function calls.

18
Q

What are macros?

A

The AOT compiler supports macros in the form of functions or static methods that return an expression in a single return expression. For example, let us take a below macro function,

export function wrapInArray<T>(value: T): T[] {
return [value];
}
You can use it inside metadata as an expression,</T>

@NgModule({
declarations: wrapInArray(TypicalComponent)
})
export class TypicalModule {}
The compiler treats the macro expression as it written directly

@NgModule({
declarations: [TypicalComponent]
})
export class TypicalModule {}

19
Q

Give an example of few metadata errors?

A

Expression form not supported: Some of the language features outside of the compiler’s restricted expression syntax used in angular metadata can produce this error. Let’s see some of these examples,
1. export class User { … }
const prop = typeof User; // typeof is not valid in metadata
2. { provide: ‘token’, useValue: { [prop]: ‘value’ } }; // bracket notation is not valid in metadata
Reference to a local (non-exported) symbol: The compiler encountered a referenced to a locally defined symbol that either wasn’t exported or wasn’t initialized. Let’s take example of this error,
// ERROR
let username: string; // neither exported nor initialized

@Component({
selector: ‘my-component’,
template: … ,
providers: [
{ provide: User, useValue: username }
]
})
export class MyComponent {}
You can fix this by either exporting or initializing the value,
export let username: string; // exported
(or)
let username = ‘John’; // initialized
Function calls are not supported: The compiler does not currently support function expressions or lambda functions. For example, you cannot set a provider’s useFactory to an anonymous function or arrow function as below.
providers: [
{ provide: MyStrategy, useFactory: function() { … } },
{ provide: OtherStrategy, useFactory: () => { … } }
]
You can fix this with exported function
export function myStrategy() { … }
export function otherStrategy() { … }
… // metadata
providers: [
{ provide: MyStrategy, useFactory: myStrategy },
{ provide: OtherStrategy, useFactory: otherStrategy },
Destructured variable or constant not supported: The compiler does not support references to variables assigned by destructuring. For example, you cannot write something like this:
import { user } from ‘./user’;

// destructured assignment to name and age
const {name, age} = user;
… //metadata
providers: [
{provide: Name, useValue: name},
{provide: Age, useValue: age},
]
You can fix this by non-destructured values
import { user } from ‘./user’;
… //metadata
providers: [
{provide: Name, useValue: user.name},
{provide: Age, useValue: user.age},
]

20
Q

What is metadata rewriting?

A

Metadata rewriting is the process in which the compiler converts the expression initializing the fields such as useClass, useValue, useFactory, and data into an exported variable, which replaces the expression. Remember that the compiler does this rewriting during the emit of the .js file but not in definition files( .d.ts file).

21
Q

How do you enable binding expression validation?

A

You can enable binding expression validation explicitly by adding the compiler option fullTemplateTypeCheck in the “angularCompilerOptions” of the project’s tsconfig.json. It produces error messages when a type error is detected in a template binding expression.

For example, consider the following component:

@Component({
selector: ‘my-component’,
template: ‘{{user.contacts.email}}’
})
class MyComponent {
user?: User;
}
This will produce the following error:

my.component.ts.MyComponent.html(1,1): : Property ‘contacts’ does not exist on type ‘User’. Did you mean ‘contact’?

22
Q

What is Non null type assertion operator?

A

You can use the non-null type assertion operator to suppress the Object is possibly ‘undefined’ error. In the following example, the user and contact properties are always set together, implying that contact is always non-null if user is non-null. The error is suppressed in the example by using contact!.email.
@Component({
selector: ‘my-component’,
template: ‘<span *ngIf=”user”> {{user.name}} contacted through {{contact!.email}} </span>’
})
class MyComponent {
user?: User;
contact?: Contact;

setData(user: User, contact: Contact) {
this.user = user;
this.contact = contact;
}
}

23
Q

What is type narrowing?

A

The expression used in an ngIf directive is used to narrow type unions in the Angular template compiler similar to if expression in typescript. So *ngIf allows the typeScript compiler to infer that the data used in the binding expression will never be undefined.
@Component({
selector: ‘my-component’,
template: ‘<span *ngIf=”user”> {{user.contact.email}} </span>’
})
class MyComponent {
user?: User;
}

24
Q

How do you describe various dependencies in angular application?

A

The dependencies section of package.json with in an angular application can be divided as follow,

Angular packages: Angular core and optional modules; their package names begin @angular/.
Support packages: Third-party libraries that must be present for Angular apps to run.
Polyfill packages: Polyfills plug gaps in a browser’s JavaScript implementation.

25
Q

What is zone?

A

A Zone is an execution context that persists across async tasks. Angular relies on zone.js to run Angular’s change detection processes when native JavaScript operations raise events

26
Q

What is the purpose of common module?

A

The commonly-needed services, pipes, and directives provided by @angular/common module. Apart from these HttpClientModule is available under @angular/common/http.

27
Q

What are the steps to use animation module?

A

You need to follow below steps to implement animation in your angular project,

Enabling the animations module: Import BrowserAnimationsModule to add animation capabilities into your Angular root application module(for example, src/app/app.module.ts).
import { NgModule } from ‘@angular/core’;
import { BrowserModule } from ‘@angular/platform-browser’;
import { BrowserAnimationsModule } from ‘@angular/platform-browser/animations’;

@NgModule({
imports: [
BrowserModule,
BrowserAnimationsModule
],
declarations: [ ],
bootstrap: [ ]
})
export class AppModule { }
Importing animation functions into component files: Import required animation functions from @angular/animations in component files(for example, src/app/app.component.ts).
import {
trigger,
state,
style,
animate,
transition,
// …
} from ‘@angular/animations’;
Adding the animation metadata property: add a metadata property called animations: within the @Component() decorator in component files(for example, src/app/app.component.ts)
@Component({
selector: ‘app-root’,
templateUrl: ‘app.component.html’,
styleUrls: [‘app.component.css’],
animations: [
// animation triggers go here
]
})

28
Q

What is State function?

A

Angular’s state() function is used to define different states to call at the end of each transition. This function takes two arguments: a unique name like open or closed and a style() function.

For example, you can write a open state function

state(‘open’, style({
height: ‘300px’,
opacity: 0.5,
backgroundColor: ‘blue’
})),

29
Q

What is Style function?

A

The style function is used to define a set of styles to associate with a given state name. You need to use it along with state() function to set CSS style attributes. For example, in the close state, the button has a height of 100 pixels, an opacity of 0.8, and a background color of green.

state(‘close’, style({
height: ‘100px’,
opacity: 0.8,
backgroundColor: ‘green’
})),
Note: The style attributes must be in camelCase.

30
Q

What is the purpose of animate function?

A

Angular Animations are a powerful way to implement sophisticated and compelling animations for your Angular single page web application.

import { Component, OnInit, Input } from ‘@angular/core’;
import { trigger, state, style, animate, transition } from ‘@angular/animations’;

@Component({
selector: ‘app-animate’,
templateUrl: <div [@changeState]="currentState" class="myblock mx-auto"></div>,
styleUrls: .myblock { background-color: green; width: 300px; height: 250px; border-radius: 5px; margin: 5rem; },
animations: [
trigger(‘changeState’, [
state(‘state1’, style({
backgroundColor: ‘green’,
transform: ‘scale(1)’
})),
state(‘state2’, style({
backgroundColor: ‘red’,
transform: ‘scale(1.5)’
})),
transition(‘=>state1’, animate(‘300ms’)),
transition(‘
=>state2’, animate(‘2000ms’))
])
]
})
export class AnimateComponent implements OnInit {

@Input() currentState;

constructor() { }

ngOnInit() {
} }