Angular | Quizlet

0.0(0)
studied byStudied by 0 people
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
Card Sorting

1/91

encourage image

There's no tags or description

Looks like no tags are added yet.

Study Analytics
Name
Mastery
Learn
Test
Matching
Spaced

No study sessions yet.

92 Terms

1
New cards

RXJS (Reactive Extensions for JavaScript)

library for working with asynchronous code by using observables (streams). It provides an Observable type, Observer, Schedulers, Subjects and operators. RxJs is used for http-requests, router, reactive forms, pipes.

2
New cards

RXJS Operators

- creation (of, from, fromEvent, interval)

- transformation map(): It takes each emitted value, transforms it, and then outputs the transformed value.

- tap(): performs a side effect (like logging) without modifying the stream

- filter(): filters values based on a condition

-debounceTime(): waits for a pause in the stream for a some time before emitting the last value. (For search input, where you wait until the user stops typing before making a request)

- take(): takes only the first N values from the stream, and then completes.

- error handling (catchError)

3
New cards

Angular rendering engine

Angular Ivy is the new rendering engine introduced in Angular 9. Ivy improves the performance of your Angular applications by reducing the bundle size, faster change detection, tree shaking

Angular Ivy uses a library Incremental DOM as part of its rendering engine. It is a rendering strategy, the idea is to update only the parts of the DOM that have changed, rather than re-rendering the entire UI from scratch.

React and Vue use Virtual DOM.

4
New cards

Virtual Dom

Virtual DOM : Каждый компонент создаёт новое виртуальное-дерево всякий раз, когда он рендерится. React сравнивает новое дерево с предыдущим, после чего вносит набор изменений в DOM браузера, чтобы привести его в соответствие с новым виртуальным-деревом. На первом шаге мы на базе реального DOM строим виртуальное дерево — для каждого элемента нужно выделить какой-то объем памяти. Чтобы отрисовать новое состояние, мы строим новое виртуальное дерево, а значит — для каждого элемента повторно выделяется нужный объем памяти. Далее старое и новое виртуальные деревья сравниваются, и если есть разница — изменения применяются к физическому DOM.

Получается, что на каждом этапе рендера нам требуется повторно выделять память в размере, необходимом для того, чтобы отрисовать дерево целиком.

5
New cards

Incremental DOM

Yes, Incremental DOM is a library. It is a lightweight, low-level JavaScript library designed for efficiently updating the DOM (Document Object Model) by minimizing the amount of changes made to it.

The core idea behind Incremental DOM is that instead of re-rendering the entire DOM when something changes, it only updates the specific parts of the DOM that have actually changed. It directly manipulates the DOM, unlike Virtual DOM (used by React), which creates a virtual representation of the DOM first and then applies changes.

6
New cards

angular.json

configuration file with settings. Such as what files are included or excluded, the build configuration, and which environments (development or production). File paths, Output paths (where the compiled files will be placed). Settings for the development server: port, live-reload(whether the app should automatically reload when files change),proxy settings

7
New cards

Dependency injection

Dependency Injection - design pattern, when class receives dependencies from outside, instead of creating it inside. F.e. class Car, it depends on Wheel class, which depends on other classes, to create class Car you need all these nested objects. DI can create for us these dependencies. Also it makes our component independent from service.

Angular has its own Dependency Injection realization. Angular checks if there is already existing instance of this service in registry, if no, then injector creates it, using registered provider and call the component's constructor with those requested services as arguments.

8
New cards

Parts of DI

1. Provider - where we describe dependency, f.e. providers array in module, provider is an object, it has a key (token, with the `provide` keyword), and useClass or useValue - from where dependency is creating. When class name and token is the same, we just write class.

2. injector - creates all dependencies and inject it in the constructor. It is used under the hood

3. Dependency

9
New cards

@Injectable decorator

To use some service in our service (f.e. httpClient), we need to add @Injectable() decorator. We say by that, that angular needs to create instance.

10
New cards

Injection Token

Injection tokens provide a way to create unique identifiers. Dependencies in Angular are usually services, but it can be string, object or function. If we need to inject a string constant, we can use InjectionToken.

We should use useValue. There are built in Injection Tokens.

const API_BASE_URL = new InjectionToken("API_BASE_URL")
[
{ provide: API_BASE_URL, useValue: 'api.mysite.com' }
]

11
New cards

useFactory

Is used when you need to provide entity based on condition.

12
New cards

useExisting

create reference to service (gets existing resolved instance and returns it)

13
New cards

StaticInjector vs ReflectiveInjector

Two different types of dependency injection systems used for managing dependencies. ReflectiveInjector was the original injector used in earlier versions of Angular (Angular 2 to Angular 4). StaticInjector was introduced in Angular 5 and replaced ReflectiveInjector to optimize performance.

StaticInjector performs dependency resolution at compile-time rather than runtime, meaning that dependencies are known before the application is run.

14
New cards

multi: true

Allow multiple instances of a service or value to be injected. It tells Angular that the provider should be added to an array rather than replacing an existing value.

15
New cards

Ways to register provider

1. By default, Angular CLI registers a provider in service itself using @Injectable({providedIn: 'root'}) decorator. In that case at the root (application) level, Angular creates a single, shared instance of service and injects it into any class that asks for it.

2. At the component level, register a service provider in the `providers` property.

3. For NgModule based applications, provider can be declared in `providers` field of the module.

16
New cards

ng-content ( content projection)

ng-content allows parents components to project html code in child components. You can write this content between child component's tags. And in child component you should specify where you want this content to be displayed, you just write there `ng-content`.

`ng-content` has attribute `select`, you can specify the selector: tag, class or attribute of content you want to display, thanks to that we can place propagated template in several places of child component:

17
New cards

:host selector

:host selector in Angular is a special CSS selector used in component styles to apply styles to the host element of a component. Without host selector it's not reachable, because it's not part of its own template, it's part of parent template.

18
New cards

Http Interceptors

Allow you to intercept and modify HTTP requests and responses before they are sent to or after they are received from a server. Interceptors are part of Angular's HttpClientModule, and they give you a powerful way to add common logic to all HTTP requests and responses.

Use cases: Adding Authorization Tokens to HTTP requests, handle errors globally for all HTTP requests instead of repeating it in each HTTP request call.

19
New cards

standalone components

Appeared in Ang14.

Components, directives, and pipes can be marked as `standalone: true`. That means it's separated from any Angular module.

It solves couple of problems. F.e. when we imported a component from Shared module, with that component we pulled all the stuff this module has, which we don't need. With standalone components, in final bundle there is no unused components. From Ang17 by default it adds standalone: true.

20
New cards

Template variable

Reference variable that you can define in your component's HTML template to reference an element, component, or directive. It is defined using the hash symbol (#) followed by the variable name.

<input #myInput type="text"> <button (click)="logValue(myInput.value)">Log Value</button>

21
New cards

ViewChild and ViewChildred

@ViewChild is a decorator in Angular that allows you to get a reference to a single DOM element or child component in your template. This reference is available in your component class so that you can interact with that element/component directly from your TypeScript code. You can call methods or access properties of the ChildComponent.

@ViewChildren is similar, but it gives you references to multiple DOM elements or child components in the template.

22
New cards

ContentChild and ContentChildren

Property Decorators. By using these decorators we can have access to content of child components it the ts file. Content it's what is located between its tags (this content in child component will be places instead of <ng-content> ).

Inlike ViewChild, ContentChild/Children are used in child component, not in parent component. But syntax is similar.

Just text can't be find with ContentChild decorator, because it isn't a DOM element, but we can find paragraph or template, or nested component. Info in ContentChild/Children will be available after ngAfterContentInit lifecycle hook will be called.
Difference between them two is that ContentChild can access first found occurrence, and ContentChindren can access to all of them in array of type QueryList.

23
New cards

Component life cycle hooks

Constructor injection of dependencies. First of all constructor is initializing, the instance of component is created, dependencies are injected, and after that component starts its life-cycle. If we write some logic in the constructor, it will run before life-cycle methods. We can omit constructor, if we don't need it. We should not write any initialization logic in the constructor, because we don't have an access for the inputs, and also there may be some errors.
Lifecycle hooks - methods which will be called automatically in the corresponding moment

1.ngOnChanges - if there are inputs it will be called before onInit, triggers whenever inputs change or initialize. If there is no inputs, it won't run. It can receive an argument of type SimpleChanges (current value, previous value, is it the first value). When your input is an object, then you should change the link to it, if you want ng on changes notice that.

2. ngOnInit - initialization (in constructor we can't access inputs) - triggers once after component checked its properties, but before component template was checked

3. ngDoCheck - runs very often, every time when change detection mechanism checks if there are changes in the component (it's not recommended to use it, use only if we don't use ng-zone, and want to launch change detection). It also will trigger ngAfterContentChecked and ngAfterViewChecked

4. ngAfterContentInit - it is called once when content projection content is initialized (when initialized that you wrote between child component's tags in parent component ). Even if child component doesn't have ng-content tags in it, this method will be called anyway.

5. ngAfterContentChecked - is called when this content was checked. First time it will run after ngAfterContentInit, and then every time after ngDoCheck

6. ngAfterViewInit - is called when component's template is initialized, including nested components templates. So it will be called only after all life-cycle hooks of child component will be called.

7. ngAfterViewChecked - when change detection mechanism checked if there are some changes in the component. First time it will be called after ngAfterViewInit method, and then it will be called every time after ngAfterContentChecked

8. ngOnDestroy - to unsubscribe. Is being called when component is deleted from DOM tree

24
New cards

Interpolation {{ }}

double curly brackets {{ }} syntax to put vars/ expressions in the template

25
New cards

ChangeDetection

The mechanism used for updating user interface, when our app state has been changed. It checks the components tree starting from the root .

It has two strategies: Default (we can omit this one) and OnPush. It is indicated in the component's decorator in changeDetection property.

Default strategy - checks all components every time when in some of them data has been changed. Check the whole tree (doesn't matter where it happened), so if some variable changed in the parent component, change detection mechanism will check for its child, even if it is empty/ doesn't use this variable. So it leads to unnecessary calculations.

On-Push - it will run in three cases:

1. we manually run markForChek() or detectChanges() or applicationRefTick()

2. data in input changed (if we receive an object in the input, and there changed one of its properties, change detection won't react (or not?))

3. event happened in DOM tree and this event has an event handler (outputs)

4. change in data, which is used with async pipe ngDoCheck will run in parent and child components)

5. also when we use signals

26
New cards

Pipes

Transform data in html template, it's written in interpolation after vertical line. There are built in pipes in Angular, as async pipe, date pipe, json, lowerCase, upperCase, slice pipe etc, but it's possible to create custom pipes. Pipes can be written one by one. To add parameter to the pipe use colon (:).

Async pipe automatically subscribes/unsubscribes to Observable/Promise when component has been destroyed (deleted from DOM tree).

- Pure pipes - it's default value, it means that changes will be noticed only when the value has been changed or if the link has been changed (if we're talking about objects).

- Impure pipe - it will notice all the changes, even if object's property has been changed, or some event in the app happened (click, keypress etc). So it will happen much more often and may affect performance.

27
New cards

Component data binding

1. interpolation double curly brackets {{ }} to put vars/ expressions in the template

2. property binding - square brackets, to dynamically set values for properties and attributes. When attribute is surrounded with square brackets, Angular waits for the expression, so it is better to remove square brackets if it's just a string. Interpolation and property binding are used to transfer data from ts file to the template.

<img [src]="mySource">
<button [disabled]="isDisabled">
<child-comp [title]="myTitle" ></child-comp> 
// will be taken as @Input

3. event binding - to react for events, f.e. click or scroll. Event-binding used to transfer data from template to the ts file

4. two-ways data binding (ngModel)

Two-way binding - to change variable simultaneously from template (f.e. input) and ts file. Or between components. It's banana-in-the-box syntax: [(name)] = "name" . Need to import FormsModule.

28
New cards

Communication between components

Input() - from parent to child component. (in the parent component pass value with data binding)

Output() - from child to parent component. You create an EventEmitter, and when event happens, you call its method emit.

29
New cards

Custom pipes

Class with decorator @Pipe, which implements interface PipeTransform with the only method transform()

30
New cards

Router

Router is used to navigate between different pages. You define routes and map them to components so users can navigate through your app without reloading the page.

  • First, import RouterModule in AppModule.

  • Add Router Outlet: In your app.component.html, add the <router-outlet></router-outlet> tag. This is where the routed component will be displayed.

  • Define Routes: In the RouterModule.forRoot() method, you define an array of route objects, where each object has a path (URL path) and component (component to display).

  • Navigate with RouterLink: You can use the routerLink directive in the template to navigate to different routes, like in the navigation links above.

  • Programmatic Navigation: You can also navigate programmatically using the Router service in your components.

31
New cards

Guards

It implements CanActivate interface. It controls whether the user can navigate to the route or leaving the route based on a certain condition. Not all the routs of the application are accessible to everyone.

Some use cases:

- restrict access to the route

- ask to save changes before going away

There are several types of guards in Angular:

  • CanActivate - decides if a route can be accesses by a user or not

  • CanActivateChild - determines if a child route can be activated

  • CanDeactivate - decides if a user can leave the route (to save changes)

  • Resolve - delays the activation of the route until some task are complete

  • CanLoad - prevents from loading Lazy Loading modules, if we don't want to show to unauthorized users the source code of the module

32
New cards

main.ts file

When you start the app, at first the code from main.ts will be executed. main.ts file is the entry point of the application. It’s where the application bootstraps (starts up) by loading the root module (AppModule). It’s responsible for setting up everything required for Angular to run in the browser, including setting up the root module (AppModule) and enabling production mode if needed.

33
New cards

polyfills.ts

polyfills.ts file in Angular is used to ensure that the application works across different browsers, particularly older ones. Polyfills provide implementations of new JS features (line Promises, Map, Set), allowing Angular applications to run in older browsers.
You may need it if you support legacy browsers like Internet Explorer

34
New cards

Angular CLI

Command Line Interface is a tool that provides a set of commands, such as generating components, services, modules, building, testing your application. It allows you to quickly create a new Angular project (ng new my-angular-app)

35
New cards

Modules

Class with decorator @NgModule , which combines components, directives, pipes, services. Angular app has module architecture, and it should have at least one root module.

In modules there some props:

  • imports - array with imported modules

  • exports - array of components, directives and pipes which are used by other module, that import our module

  • declarations - set of components, directives, and pipes

  • providers (services),

  • bootstrap - array of components as entry points in your application

36
New cards

Components

Main building blocks, defines app view. Each component encapsulates its own HTML, CSS, and TypeScript. It is marked with @Component() decorator. Decorators provide specific functionality, for components it's adding a template.

Component has a selector, HTML template and styles. Components are organized in a hierarchy.

37
New cards

Scoped Styles (encapsulation)

View encapsulation is a mechanism to scope styles to a particular component.

  • Default. Angular automatically scopes the styles for each component by adding unique attributes to the HTML elements. So styles only apply to the elements inside component, not to other parts of the application.

    <h1 _ngcontent-c0>Scoped Style in Angular</h1>

  • ViewEncapsulation.None - The styles defined in the component will apply globally

38
New cards

Services

Store logic not related to view of components. With services we use @Injectable decorator, that allows to inject dependencies to the class.

Service should have specific well-defined purpose. Usual tasks in services: fetch data from server or validate user input. Since service is injectable, logic it it can be reused by many components and other services.
Services are singleton by default when they are provided at the root level. This means that there will be only one instance of the service shared throughout the entire application, and this instance is reused whenever the service is injected into different components

we register one instance for the app. Services are registered usually in module in providers array. To use service you need to inject is, to do so you pass in constructor private variable and service type.

39
New cards

@Directive

It's a class with decorator @Directive that gives specific behavior to DOM elements.

  • components (it's also directives, with its template). Component's interface extends Directive.

  • structural directives - they change DOM structure ( they have asterisk symbol before the name, in latest versions use 'at' symbol @) - ngIf, ngFor, ngSwitch. It's forbidden to write two structural directives on one DOM element, but you can use ng-content. hidden attribute adds display: none and *ngIf removes element from DOM tree. *ngFor - has a tracked by property - it ties the view to a key, and if the key is the same, so the element did not changed, then angular won't redraw this element, so it's for optimization.

  • attribute directives - they change appearance. ngStyle - to dynamically add styles; ngClass - to add class depending on variable

In 17 Angular version there is new syntax for structural directives If, For, Switch.

Directive (as a component) can receive some data from outside with @Input.

40
New cards

TemplateRef and ViewContainerRef

TemplateRef and ViewContainerRef are primarily used when creating custom structural directives. It is used to manipulate the template content and dynamically add or remove views in response to some condition.

  • TemplateRef - a reference to the template structure that Angular will render dynamically (inside an ng-template)

  • ViewContainerRef - Represents the container into which the template is rendered. It provides methods to manipulate the DOM (like createEmbeddedView() to insert a template into the DOM or clear() to remove it).

41
New cards

@HostBinnding?

Used in directives. HostBinding is a decorator that allows you to bind properties or attributes of the host element (the element to which a directive is applied) to a value in the directive class. It is commonly used when you want to update the host element's properties, such as class, style, or attributes, based on the directive's state or logic.

42
New cards

@HostListener

Used in directives. It's a decorator witch listens to a DOM event on the host element and reacts to that event by executing event handler method. Usually used for custom directives (), when you add directive's name on the element, and want this event to be handled in this directive handler.

43
New cards

ng-template (TemplateRef)

We create html template, but ng-template isn't shown by default. If we just will write some elements inside ng-template - it won't appear on the screen. You need to specify with ng-container or in structural directive (in else condition) where you want to show ng-template and what data you want to propagate to it. Ng-template has ElementRef— which is the reference to html element, where our ng-template is placed in the DOM-tree.


<div *ngIf="smth; else myTempl"></div
<ng-template #myTempl></ng-template>

44
New cards

*ngIf vs [hidden]

ngIf removes element from the DOM tree, [hidden] attribute just hides it, adding display none

45
New cards

ng-container

It is a wrapper which doesn't increase nesting level. When you write ng-content, you won't see it in the browser. It is usually used with ng-template.
ng-container has an attribute *ngTemplateOutlet(). If we write *ngTemplateOutlet() attribute, the content of ng-container will be ignored. *ngTemplateOutlet() has two arguments, first one - is a tag of the ng-template, what we need, and second one is a context object, we can propagate some data with it to ng-template element.

// place it where you want to see your template

<ng-container 
	*ngTemplateOutlet="myTempl; 
	context: { $implicit: 'hi'}"
>
 content will be ignored 
</ng-container>
// ng-template can be placed anywhere

<ng-template #myTempl let-myInnerVariable> {{ myInnerVariable }} </ng-template>

// instead of myInnerVariable will be shown hi

46
New cards

Singleton

Singleton pattern means that a service is created only once and shared across the entire application. So, whenever you need that service in any part of the app, you get the same instance of the service with the same data, instead of creating a new one each time.
When service in Angular has providedIn: 'root', it will be singletone.

Advantages:

  • Consistency: the value stays the same no matter where you use it in your app.

  • Memory-saving: You don’t waste resources by creating a new service every time, Angular uses the same one.

  • Shared Data: You can easily share data or logic across different parts of your app.

47
New cards

Decorator

decorator is a special function that adds additional functionality or certain behavior (metadata) to classes, methods, properties. Decorator is used with @ symbol before its name. F.e.: @NgModule, @Component, @Directive, @Pipe, @Input.

48
New cards

Observable

An Observable in Angular (and RxJS, which Angular uses) is a powerful way to manage asynchronous operations, such as handling data streams, events, or HTTP requests. It allows you to subscribe to a source of data and react to updates as they occur, like receiving new values.

It is like asynchronous array, where data is updating. The difference from promise - you need to subscribe to receive data from it.

49
New cards

Ways to create observables

It's RXJS operators, you can just write it in code. To receive data from these operators, you should subscribe on it.

  • interval() - creates an Observable that emits sequential numbers in specific interval, you need to unsubscribe

  • of() - to transform primitive data type to an Observable, it takes arguments, and creates an Observable from it, it will finish automatically when arguments are ended

  • from() - it is similar to of operator, but from takes an iteratable argument, for example an array, it will stop automatically when this array will end

  • fromEvent() - creates an Observable when an event (like click) happened on some element, and you specified in the fromEvent arguments an element and the event. And you need to unsubscribe, when you don't need it anymore

  • It is also possible to create Observable with the class, new Observable, but it's not used often

    interval(1000).subscribe()
    fromEvent(document, 'click').subscribe()

50
New cards

Methods in Observables

When observable is ready to produce new portion of data, it iterates over its subscribers and calls corresponding callback. The methods next(), error(), and complete() do not exist directly on the Observable itself. Instead, they are called on the subscribers that are passed to the Observable. These methods are part of the Observer object.

  • next(value): if it received new portion of data, Observable will call the next() method on the observer. This is how the Observable pushes data to the subscriber.

  • error(err): If an error occurs in the Observable (for example, if something goes wrong in an HTTP request), the Observable will call the error() method on the observer. This signals to the subscriber that something went wrong and terminates the stream.

  • complete(): Signals that no more values will be emitted, and the stream is finished. The complete() callback in the subscriber is triggered at this point.

As a developer, you don’t directly call the next(), error(), or complete() methods yourself. These methods are called automatically by the Observable when the data stream is being processed.

51
New cards

difference between Promise and Observable

They both work with asynchronous code

1. But promise works if the only one event

2. Promise works without subscription

3. You can unsubscribe from observable

4. You can use rxjs operators with observable( map, filter, reduce, retry)

52
New cards

Subject, BehaviorSubject, ReplaySubject, and AsyncSubject

It behaves like an Observable (can emit values) but it’s also like an Observer (can receive values).

1. Simple Subject - кShares the same value stream to all subscribers. If you push values into the Subject, any subscriber who subscribes will get those values. The value stream shared among multiple subscribers. You can call next next method to push new value.

2. BehaviourSubject it stores only the current (last) value of the stream. It needs an initial value. The most popular type of subject. Has getValue method, to return current value and next() - to push new value.

3. ReplaySubject Remembers a set number of past values and replays those values to any new subscribers. You can specify how many of the most recent values you want to store. For optimisation

4. AsyncSubject — Only emits the last value when the observable completes.

53
New cards

Constructor and ngOnInit

  • The constructor is called first (when the component class is instantiated), but Angular doesn’t yet have all the information about the component's inputs, view, or other dependencies at that point. When you write logic inside the constructor, you run the risk of trying to access data or perform operations before everything is ready (e.g., before Angular has finished setting up inputs, views, or other dependencies).
    If you write logic that depends on external resources (like HTTP requests, services, or data fetching), it can result in race conditions or null values.
    The view (HTML template) is not yet initialized when the constructor is executed. So if you try to interact with the DOM, this logic will not work.
    Component Inputs are not yet set when the constructor runs. If you try to access an @Input() properties, it will be undefined.

  • ngOnInit() ensures that the component is fully set up, making it the right place to handle logic that relies on inputs or the component's lifecycle.

54
New cards

Jasmine: Spy

spy is a function that allows you to track calls to methods, check arguments passed to those methods, and control their behavior. Spy returns mocked value, so we can understand whether the function was called, how many times, with which parameters.

55
New cards

Protractor

Protractor is an end-to-end testing framework specifically designed for Angular applications, though it can be used for non-Angular apps as well. It automates browser interactions. However, since Protractor is being deprecated, it might be a good idea to consider alternatives like Cypress or Playwright

56
New cards

TestBed

TestBed is a core utility in Angular’s testing framework, which is provided by @angular/core. It's used for configuring and creating an Angular testing module in unit tests.
In Angular, components, services are often have other dependencies. In a unit test, we need to create instances of these components and inject dependencies, without actually bootstrapping the application.

TestBed provides a testing module, similar to how the main Angular module (usually AppModule) works in a real application. It allows to configure a mock environment for your tests.

57
New cards

Zone js

It is a library that allows us to manage asynchronous events.

Every time component is created

1. Angular creates a new zone for it

2. Checks for updated

3. If there are changes it pushes Change detection mechanizm.

How zone.js works?

In general, zones provide a mechanism to intercept the scheduling and calling of asynchronous operations. Interceptor logic can execute additional code before or after the task and notify interesting parties about the event. These rules are defined individually for each zone when it’s being created.

Сhange detection is not part of zone.js, it is just used to trigger it. If you remove zone.js then you can still call change detection manually. You can explicitly say that this function needs to run outside Angular zone with the ngZone.runOutsideAngular(). To enable automatic change detection, Angular implements NgZone service that forks a child zone and subscribes to notifications from this zone.

But since Angular 18 Zoneless Change Detection appeared.

58
New cards

АОТ Ahead-of-Time

The Ahead-of-Time (AOT) compiler is a mechanism in Angular that compiles your application at build time, rather than at runtime (which is the case with the Just-in-Time (JIT) compiler).

Since AOT precompiles the code, it significantly reduces the time needed for the browser to compile the application. This results in faster rendering and better performance.

Smaller Bundle Size: AOT eliminates the need for the browser to compile templates and code, leading to smaller JavaScript bundles.

59
New cards

Just-in-time Compiler

The Just-in-Time (JIT) compiler in Angular is the mechanism that compiles TypeScript and HTML templates into JavaScript code at runtime (i.e., in the browser) rather than at build time.
JIT is still used, but mainly in development. For production builds, AOT is recommended because it produces faster, smaller, and more optimized applications.
In Development: Angular uses JIT by default when you run the application in development mode using commands like ng serve. This provides quicker build times. : For production builds, Angular automatically switches to AOT mode when you run ng build --prod.

60
New cards

Lazy loading

Lazy loading in Angular is a technique used to load specific parts of your Angular application only when they are needed. It is configured in Angular using the loadChildren property in the router.

61
New cards

ActivatedRoute

ActivatedRoute is a service in Angular that provides information about the current active route.You can use it to access route parameters((like id or username)), query parameters and route data.
It supports both snapshot-based access (gives the static information at the time the component is initialized) and reactive access using Observables (dynamic data, if you want to listen to changes in route parameters).

62
New cards

Dynamic components

Used if component shouldn't be shown right after page loading. F.e popup windows, notifications. It can be rendered in a template with NgComponentOutlet, or in ts file with ViewContainerRef.

To create dynamic component we need to import ViewContainerRef, and in the constructor we need to receive a link to container. This container has method createComponent(). To put data to dynamic component you should use setInput. Get data from component is not easy, Outputs do not work.
Can be used for: dialogs, notifications

63
New cards

Reactive forms

Для их использования нужно импортировать модуль ReactiveFormsModule.

Создание и валидация Angular reactive forms осуществляется прямо в контроллере, т.е. формы пишутся программно, а не в шаблоне. Но в шаблоне все равно пишется весь html, и он связывается с переменной form в компоненте(тс) с помощью директивы [formGroup]. Внутри основной формГруппы можно создавать дополнительные подгруппы - так можно логически объединить данные. Подгруппы обозначаются директивой formGroupName, а поля группы — директивой formControlName.

FormControl - отслеживает значение и статус валидации элемента формы.

FormGroup - отслеживает значение и статус валидации группы

Ангуляр сам добавляет специальные классы инпутам, которые не прошли валидацию(ng-invalid, ng-touched).

64
New cards

Two ways to write forms

1. Template-driven forms are simpler to set up and use Angular's directives( ngModel and ngForm) to handle form inputs. They are best suited for simpler forms. Validation with attribute required and pattern.

2. Reactive forms provide more control and are more flexible for complex forms. They are defined in the component class. Forms are defined in the component using FormGroup, FormControl, and FormBuilder. You can apply built-in or custom validators( Validators.required, Validators.email, Validators.pattern('[0-9]{10}') - checks for regular expression).

65
New cards

HttpClient

HttpClient is a service in Angular that allows you to make HTTP requests to communicate with a backend server or an API. It is part of the @angular/common/http module and provides a simple and powerful way to interact with web services. Need to import HttpClientModule, it is based on RxJs, so you need to subscribe to send the request.

66
New cards

compilation of angular apps

compilation refers to the process of transforming your TypeScript into JavaScript and scss to css that can be run by a browser. This process also includes optimizing your app by removing unused code, minifying assets.

1. TypeScript Compilation (tsc)

Before Angular can compile the app, TypeScript must be compiled into JavaScript. Angular uses TypeScript, which is a superset of JavaScript that adds type safety and other features.

The TypeScript compiler (tsc) is responsible for converting TypeScript files (.ts) into .js files. This process is handled by the Angular CLI during the build process.

2. Angular Compilation

Once TypeScript has been compiled, Angular performs its own compilation of templates and components. There are two modes of Angular compilation(AOT and JIT)

<p><strong>compilation</strong> refers to the process of transforming your TypeScript into JavaScript and scss to css that can be run by a browser. This process also includes optimizing your app by removing unused code, minifying assets.<br><br><strong>1. TypeScript Compilation (</strong><code>tsc</code><strong>)</strong></p><p>Before Angular can compile the app, <strong>TypeScript</strong> must be compiled into <strong>JavaScript</strong>. Angular uses <strong>TypeScript</strong>, which is a superset of JavaScript that adds type safety and other features.</p><p>The TypeScript compiler (<code>tsc</code>) is responsible for converting TypeScript files (<code>.ts</code>) into <code>.js</code> files. This process is handled by the Angular CLI during the build process.</p><p><strong>2. Angular Compilation</strong></p><p>Once TypeScript has been compiled, Angular performs its own compilation of templates and components. There are two modes of Angular compilation(AOT and JIT)<br><br></p>
67
New cards

Tree Shaking

When app is building, unused code will be deleted from the final bundle - this process is tree shaking. Usually if you don't use standalone component, even if you import it, it won't appear in final bundle. But if you import some module in the standalone component, it can be in the final bundle.

68
New cards

NGXS NGRS

Why do we need it: single source of trouth.

Way to manage the state of your application in a centralized place. Store holds the shared data that components might access or change.

NGXS:

  • Define State: State class represents your application’s data.

  • Dispatch Actions: Actions are events that describe something that has happened in the application, like "load data", "add item. To update the state, you dispatch actions.

  • Selectors: After the state is updated, you can use selectors to access specific parts of the state in your components.

69
New cards

High-order mapping operators

Transforms each emmited value to an Observable.

F.e. when you type smth in input, and you want for each value make a request to the backend. Higher order observable is an observable, which values are also observables. With such observables we can use higher order mapping operators.

70
New cards

switchMap

Cancels the previous observable when a new one comes in. When to use: f.e. user clicks to some item, we request information about this item, but user clicks to another item, so we don't need to wait information about the previous item, we will request the next one.

71
New cards

mergeMap

It keeps previous values, but the order of these values can differ, which was first processed, it will go first.

Common use case: when you need to make multiple asynchronous requests in parallel and merge their results.

72
New cards

concatMap()

Similar to `mergeMap()`, but it waits for each event to complete before moving on to the next, so it will keep all the values and the order. It can be used when you need to keep the order.

73
New cards

exhaustedMap

While it is processing one value, it ignores the other values that comes in, and takes another value only when the previous is finished. Can be used for throttling.

74
New cards

Framework vs Library

Angular is a complete framework. It gives you everything you need to build an app, like routing, state management, forms, and more, built into the framework.

React or Vue is just a library for building UI components. If you need routing, state management, or other features, you’ll need to use separate libraries (like React Router or Redux).

75
New cards

ContentChild Parameters

- static - ContentChild has static parameter, by default it is false, which means that decorator can access to content after it was initialized. If change it to true, then we can access data in ngOnInit (but it's not recommended, because content won't be updated, as it it static).

- read - it is on both ContentChild/Children decorators (same as in ViewChild/Children)

- descendants - indicates whether nested components should be included or not. By default it is true. F.e. when in our component there is nested component which is also has nested component. If change it to false, then search will be only among direct descendants.

76
New cards

ViewChild/Children parameters

Optional parameters (can be combined):

  • static - ContentChild has static parameter, by default it is false, which means that decorator can access to content after it was initialized (that's why we have access only in ngAfterViewInit). If change it to true, then we can access data in ngOnInit (but it's not recommended, because content won't be updated, as it it static).

  • read - it is on both ContentChild/Children decorators. It's like a filter of data which we receive. F.e. you can specify which type of selector you need. If there is a <p> with template variable text, and there is <nested-component> with the same template variable, and you want receive only components, you are not interested in just paragraphs. So with read parameter you can filter out paragraph, and receive only component (by specifying class name of the component ).

  • descendants - indicates whether nested components should be included or not. By default it is true. F.e. when in our component there is nested component which is also has nested component. If change it to false, then search will be only among direct descendants.

77
New cards

Memoization

Memoization is the process of caching the results of expensive function calls and returning the cached result when the same inputs occur again, which can help improve performance.

78
New cards

Pull vs Push Model in Observable

Refer to how data is delivered to the observer.

  • pull - the data should be requested by the subscriber. The Observable waits for the subscriber to ask for the data before it starts producing it. It is like a lazy request. The Observable doesn't emit data until a subscription happens.

  • push model, the data is automatically sent to the subscriber without them having to request it each time. F.e. Event-driven programming (like user input ) is usually a push model, where the Observable "pushes" new data to its subscribers as soon as it's available.

79
New cards

Hot vs Cold Observables

  • Cold Observables: every time a new subscriber subscribes, the Observable starts emitting data from the beginning. Each subscriber gets its own independent set of values (like a fresh copy of the data). Follow a pull model because they wait for the subscription before starting to emit data. f.e. HTTP requests are typically cold. Each subscriber will get its own response.

  • Hot Observables: the data is produced and emitted even before any subscriber subscribes. So, when a new subscriber subscribes, it starts receiving the data from that point onward, not from the beginning.

    Follow a push model because starts emitting data even without a subscriber, and new subscribers will receive whatever is available at the time they subscribe.

    F.e Mouse events are hot.

So, when we say a regular Observable is Cold, it’s because the Observable emits values only after you subscribe. A Subject is Hot because it starts emitting values immediately, whether or not there are any subscribers.
Regular Observable = Cold Observable: It doesn’t emit data until there is at least one subscriber.
Subject = Hot Observable: It emits data regardless of whether a subscriber is present.

80
New cards

preloading strategies

1. No Preloading (Default)

By default, Angular only loads modules lazily when the user navigates to a route for that module. No preloading happens. Modules are loaded only when their route is visited.

2. PreloadAllModules

With the PreloadAllModules strategy, Angular will preload all lazy-loaded modules after the initial application load.

3. Custom Preloading Strategy

You can also create your own custom preloading strategy. This allows you to implement more control over which modules get preloaded and when.

For example, you might want to preload only some modules based on certain conditions.

81
New cards

angular

Is a a TypeScript-based framework for building single-page applications. It is developed by Google. A lot of technologies are already included in the framework (that's why it is framework), as forms, routing, http client etc. In Angular every entity - it's a Class.

82
New cards

Standalone component (directives/pipes)

Appeared in Ang14.

Components, directives, and pipes can be marked as standalone: true. That means it's separated from any Angular module, you don't need to declare it in [NgModule].

And you need to specify what it needs in the imports section (f.e. CommonModule)

It solves couple of problems. F.e. when we imported a component from Shared module, with that component we pulled all the stuff this module has, which we don't need. With standalone components, in final bundle there will be no unused components. From Ang17 by default it adds standalone: true.

Round dependency error - when you import Module1 in Module2 and Module2 in Module1 - also solved with standalone components.

83
New cards

Directive's ExportAs property

Directives (so components too) have a property exportAs, and it allows to give a name to that directive and be able to refer to it from anywhere in the template:


@Directive {
	selector: 'my-directive',
	exportAs: 'kek'
}

84
New cards

Web Components (Elements)

Web Components are a set of web platform APIs that allow developers to create reusable, custom HTML elements that can be used in web applications, regardless of the framework or library. These components are encapsulated, meaning they have their own style and behavior. Angular supports the creation and use of Web Components (also called Custom Elements).
These components are not tied to a specific framework, and they are based on standard web technologies, such as HTML, CSS, and JavaScript. This means you can use Angular to build a Web Component and then use that Web Component in any other project or framework, whether it’s Angular, React, or a plain HTML page.

You need to import Angular's @angular/elements and use createCustomElement to convert the Angular component into a custom element.

85
New cards

Change Detection

The mechanism used for updating user interface, when our app state has been changed. It checks the components tree starting from the root .

It has two strategies: Default (we can omit this one) and OnPush. It is indicated in the component's decorator in changeDetection property.

  • Default strategy - checks all components every time when in some of them data has been changed. Check the whole tree (doesn't matter where it happened), so if some variable changed in the parent component, change detection mechanism will check for its child, even if it is empty/ doesn't use this variable. So it leads to unnecessary calculations.

  • On-Push - it will run in three cases:

1. we manually run markForChek() or detectChanges() or applicationRefTick()

2. data in input changed (if we receive an object in the input, and there changed one of its properties, change detection won't react (or not?))

3. event happened in DOM tree and this event has an event handler (outputs)

4. change in data, which is used with async pipe ngDoCheck will run in parent and child components)

5. also when we use signals

86
New cards

Zone.js disadvantages

Angular in its latest releases promotes Zoneless Change Detection — mechanism of change detection without zone.js library. For this purpose signals were created. Without signals, Angular relies on change detection cycle to find if there are some changes. But there are some problems with change detection:

  • it runs very often, even if data has not changed (f/e you write onClick=0). It impacts the performance.

  • change detection mechanism uses Zone.js library, that increases the bundle size

  • zone.js doesn't tell angular, which component, or which part of component has changed, so every time change detection cycle runs, whole component tree gets rerendered

87
New cards

Signals

Appeared in Ang16. You can think of it as a value plus the change notification, Angular automatically applies those changings to the view.

Signals is an alternative way of detecting changes in the data and update UI. So Angular can get rid of Zone.js. With Signals we don't have automatic change detection, developer should tell Angular when data changes.

Do signals replace RxJS? No, you can combine signals and observables. You can create signals from observables and observables from signals

88
New cards

Types of Signals

  • Writable signal

quantity  = signal<number>(1)
// Signals can contain any data type. Default value is required
quantity() // can get current value by calling its getter function
this.quantity.set(2) // can replace value with set function
this.quantity.update(qty => qty * 2) // can update value based on current value
  • Computed signal

    You can create a computed signal, it recomputes when its dependent signals change. Computed value is memoised and reused the next time this value is read. Computed signal is read-only.

exPrice = computed(() => price * this.quantity())
  • Effect

    You can use an effect, if you want to run some code when the signal changes. It will re-executed when a dependent signal changes.

effect(() => console.log(this.quantity())

89
New cards

@Attribute (alternative to Input)

To decrease the amount of checks we can use @Attribute decorator. This decorator allows to provide static attributes values to child components through their constructor (not through @Input decorator). So in this case we have access for such attributes in the constructor ( not in ngOnChanges method). It can be used when we work with static data, which isn't change during component life cycle, so change detection mechanism checks it only when component is initializing and won't track them in the future. It is good for performance.

So it's basically another way to write @Input, when you don't use dynamic values in the attributes, it will improve the performance.

90
New cards

How to unsubscribe?

1. Subscription has an unsubscribe method; call it in ngOnDestroy method

2. async pipe returns the latest value, when a new value is emitted, async pipe marks the component to be checked for changes. When the component gets destroyed, the asyncpipe unsubscribes automatically

3. in pipe: take(n times), takeUntil(notifier) -until a notifier Observable emits a value; takeWhile() long as the emitted value passes the condition

4. in pipe: first operator: it emits the first value and completes (same as take(1))

5. @ngneat/until-destroy package to auto unsubscribe observables: pipe(untilDestroyed(this))

91
New cards

HTTP-interceptors

Interceptor (перехватчик) - helps us to modify HTTP Request by intercepting it before it will be sent to the Server. It can also modify the response from the server. We can use it to add custom headers to the request or log the response.

  • One of the main use case - adding an authorization token. We could do this manually by adding this header to every request, but with interceptor it's easier.

  • Another case - to log the errors, generated by the request

92
New cards