Angular Notes

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 19

State management

View encapsulation

Query string parameters

DOM

Deep selector

AJAX Call

Working of Angular files – how does th program actually work

Downloading specific version

Typescript getting started, Visual studio course

Enum, interface, class

Package-lock

Standalone: true. component is standalone - which means we don't have to use Angular modules or NgModules to define

the template dependencies.

Class: construct that allows us to create a type with properties that define the data elements and methods that provide

functionality.

Methods: defined within the class body after all of the properties.

Decorator: function that adds metadata to a class, its members, or its method arguments. A decorator is a JavaScript

language feature that is implemented in TypeScript. The scope of the decorator is limited to the feature that it decorates.

Angular:

open source, front-end framework developed and maintained by Google, designed for building modern, dynamic, and

scalable web applications.


Angular is a combination of prewritten code, useful tools, and some structured guidelines, all packaged together with a

clear purpose, help you build web applications of any size. This combination is called a web framework

AngularJS: all versions that start with 1 – Misko

Angular 1 was MVC (model-view-controller)

AngularJS: view or a template, and the view would refer to a controller, and your controller would expose models or

objects that represented your data.

In Angular, you have a component, and that component has an associated template. And, as with Angular 1, you have

models that represent your data. So at a glance, you can kind of relate these together. However, in Angular 1, the

template was kind of in control. Your template would identify one or more controllers that controlled sections of your page,

whereas in Angular, components and templates really are one to one. In fact, you can kind of consider the template to be

a part of the component, and you can actually write your code like this and have your HTML right inside your component if

you choose. In this way, a component in Angular is actually more comparable to a directive in Angular 1. In Angular 1, you

could define a directive that allowed you to basically create custom HTML elements, which encapsulated both display and

functionality in a more cohesive unit. If you wanted a sortable list component that let you display an array in a stylized

table with sortable columns, you could just create a directive that gave you a sortable list element. And the directive

contained all the logic and HTML to make it all come together. Something about the directive bringing it all together made

it feel very cohesive. That's basically what components are, except it feels a lot smoother. As awesome as directives

were, they often felt clunky, and you'd run into weird edge cases that were quite difficult to solve. Components feel much

more smooth.

Angular is a JavaScript framework for building client-side applications.

main.ts - app.config.ts - app.routes.ts

index.html file - root Angular module to bootstrap our root component

Angular module: NgModule


main.ts file -

angular.json file - used by webpack.config for our site, it causes main.ts file to be loaded when our app first loads.

main.ts file is loaded by webpack via the angular.json file. Then the main.ts file loads our app.module, and that makes

Angular aware of our AppComponent. Then our index.html file is loaded in our browser, and it loads our app.component,,

which uses this template here, and that's it. So that's the basics of how to Bootstrap an Angular app.

node_modules: contains all libraries installed by the CLI as defined in package.json file

src folder contains the source code for our application

app folder: module's components, services, and other files for our application

assets folder: images or assets

environments folder: sets up build environments - development and production. The CLI picks the appropriate

environment file based on the flags we use.

index.html file is the first file downloaded when a user accesses our application.

Main.ts file that bootstraps our application

The polyfills file aids in supporting both evergreen and classic browsers. Polyfills add code to allow functionality written for

modern browsers to work in older browsers. By default, it is set up to support evergreen browsers as stated here. Here is

a style sheet for applicationwide styles.

test file sets up for testing

browserslistrc file: defines list of browsers and browser versions that application will support. It's used by the build system

to build bundles appropriate for your supported browsers.

editorconfig file: provides some standard settings for your editor.

gitignore: tells Git which files to ignore for checking in to Git. node_modules folder is included in this list.

angular.json file: CLI configuration file for our local install of the Angular CLI. This file is used to configure how the CLI

generates code and works with our files.


karma.config file sets up Karma, which is a JavaScript test runner.

README

tsconfig files: TypeScript configuration

.angular folder - used by compiler for caching to improve compiler performance,

.vscode folder - contains configuration scripts for VS Code

When we use the ng serve command, CLI builds application and outputs it as a set of bundled JavaScript and map files.

Vendor.js - contains Angular and third-party libraries imported into our application

Polyfills.js - contains polyfills declared in the polyfills.ts file. Contains code needed to support a variety of browsers and

browser features.

style files are our styles

Main.js contains our application code

runtime.js Webpack loader.

Webpack is the technology behind the compilation and bundling process. These files are generated in memory and are

not available to find on disk.

The CLI injected the needed script tags to pull down all of these bundles

Build:

Cache busting: Every time we update something in our code, it needs to be redeployed to the server. We expect the new

version of the files to be downloaded by the browser when a user accesses our application. But for performance reasons,

the browser may have cached those files. By changing the file names using a hash, the browser will download the latest

version because the file names won't match its cached versions.

Zone.js and Change Detection


Zone.js is the key to Angular's change detection.

Zone creates a wrapper around all of Angular's asynchronous operations in the browser such as user interactions, HTTP,

timers, and any other event that can cause changes in state.

Zone knows when any of these operations completes.

Angular, in turn, subscribes to notifications from zone for whenever one of these operations completes. This let's Angular

know that it can run its change detection algorithms and re-render anything that has changed because zone doesn't notify

Angular until all code that deals with the state change completes, this assures that Angular minimizes any rendering turn

and makes it efficient. Of course, Angular implements many other modern methods to minimize your rendering time and

makes many other optimizations to keep your application performant, but change detection is a big piece of this.

Rendering Targets

Angular is built to allow itself to be rendered to any number of devices by changing the rendering engine.

Angular comes with two packages that are used by default to enable rendering to the browser and the DOM:

browser-platform and the browser-platform-dynamic libraries

They allow both just-in-time compilation and pre-compilation for browsers, but Angular supports many different rendering

targets currently and may even support more in the future.

The most popular rendering targets currently are, the browser, server-side rendering with Angular Universal, mobile

devices, and desktop apps. Now many of these targets are made easier through other technologies such as Ionic and

Electron which allow you to just render for the browser and they build a mobile or desktop app around your browser

experience.

Typescript:

You might hear Angular referred to as a JavaScript framework, but Angular apps are created using TypeScript, a

programming language that's built on top of JavaScript. People often refer to TypeScript as a superset of JavaScript

Code written in TypeScript when compiled becomes JavaScript, enabling it to run in the browser.

TypeScript as a language that fixes a lot of the issues that tend to come along with using JavaScript, and it gives us

cleaner code and less errors at the same time.


NodeJs:

Modern browsers include a JavaScript engine to run JavaScript. These browser JavaScript engines allow to manipulate

the html and CSS styles of a page and access data from an API server.

Node.js allows to run JavaScript on computer. Node packages install little JavaScript libraries and are managed with node

package manager (NPM)

Server Side Rendering

Server-side rendering: process of rendering initial page view on the server so the server creates the HTML and the CSS

and sends it down to the browser, instead of your front-end framework, the JavaScript down there doing this job down on

the client. This makes the initial page view much faster and more parseable by search engines.

Client-side web applications:

User accesses specific URL - server associated with that URL is located and sent a request. The server responds by

returning its default web page, index.html. The browser receives and processes that index.html file. For an Angular

application, the index.html file contains script tags referencing the application files that were transpiled and bundled into

several JavaScript files. These application files are then downloaded to and processed by the browser, and the

application's main page appears. The index.html file contains that main page for the application. BrowserModule: registers

important application service providers, such as error handling. The bootstrap array defines the startup component of the

application

Server-side Rendering

Server-side rendering with Angular happens through a tool called Angular Universal. The concept is simple, but the

implementation is quite complex. We'll take a quick look at the benefits and the overall flow of server-side rendering with

Angular. Now, server-side rendering has a few key benefits. First is performance. Performance is increased by two

methods. Server-side rendering reduces the initial download size and a server-side rendered page isn't necessarily

smaller than a client-side rendered one, but since you need just the HTML, CSS, and a little JavaScript and images for the
one page view that your user is going to see, by avoiding downloading all the code for your framework and all the code

and templates for further views, the savings in time can be significant to that first rendering and can make a big difference

in user satisfaction. Server-side rendering also increases performance by reducing the render time. Instead of having your

client-side framework parse templates, build DOM nodes, and then wait for the browser to render all of this, the browser

just parses the HTML you give it and displays it. Again, this reduces the delay until your user sees the site working. The

second main benefit of server-side rendering is search engine optimization. Since Google does execute some client-side

JavaScript, this can be of a limited benefit, but it can still make a big difference, especially if you're relying on other search

engines or relying on Twitter or Facebook to correctly show thumbnails of your home page. Angular Universal has a

couple of options for its mode of operation. First is full prerendering, which involves running a development time process

which will take your application and create HTML for each of the views. Then you take that HTML, load it onto some kind

of a CDN, or content delivery network, and then when people hit your site, they get fast initial views. Then afterwards,

Universal will make a switch on the client to a regular client-side rendered app. The other option is dynamic prerender. In

this case, whenever a request is received by your web server, the requested page is then built by Angular Universal and

the rendered HTML and CSS is sent down to the browser, and after that, the switch happens. Currently, only Node and

ASP.NET Core are supported in this mode. With either method, once the browser has the prerendered HTML, Universal

kicks in and downloads the full app, including the Angular framework, and then in a hidden div, it boots your application,

renders the current page, replays any events the user has done so far to the current page to maintain the state, and then

swaps the display to this client-side dynamic app instead of the server-side rendered one. In either mode, you can get a

working website up and running for your user without first having to download not only all the code that you wrote, but the

Angular framework itself. Now again, this may seem simple, but it's really quite complex and setting it up does require a

bit of work, but it can really pay off in the right situation.

Angular CLI:

npm install -g @angular/cli

ng new ‘name’

ng g c ‘name’
Component: large projects into smaller parts

Components are self-contained chunks of functionality managing how something shows up for the user and all of the logic

for that piece of your application.

DataBinding:

interpolation – always string

Interpolation is used when you just need to display that data, such as when displaying the username in an h2 like we are

here

Property – other than strings like true and false values

a property binding is used when you want to bind the data to the property of a DOM element

statements: follow event binding and put in quotes

expresson:

An interface is a specification identifying a related set of properties and methods.

Directives:

Structural: change the shape of DOM – add or remove html elements from dom

logic in your templates through the use of directives.

This allows you to apply conditionals, loop through lists, set up forms, apply styles, and a lot more.

special instructions placed inside of HTML elements to modify behavior or appearance of those elements.

controlling the flow of a program: control the visibility,

ngFor
Services:

When you need to do some heavier work, something that'll be used all across the entire application, things like

authentication, working with data, or maybe notifications, you'll use what Angular calls services.

share code and data between components and other parts of the application

fetching data from APIs, managing authentication, implementing business logic, or providing other custom functionality

that you need to use across your application

Injectable

Services or providers get registered in the root injector, so they're available across Angular modules

component can create an instance of the service class and use it. But the instance is local to the component, so we can't

share data or other resources.

Register the service with Angular. Angular then creates a single instance of the service class, called a singleton, and

holds onto it.

Angular provides a built-in injector. We register our services with the Angular injector, which maintains a container of

created service instances. The injector creates and manages the single instance, or singleton, of each registered service

as required.

Dependency injection: coding pattern in which a class receives the instances of objects it needs, called its dependencies,

from an external source rather than creating them itself.

Injectable decorator required when you inject a service which also injects other services as dependencies of its own.
Constructor: Every class has a constructor that is executed when an instance of the class is created. If there is no explicit

constructor defined for the class, an implicit constructor is used. But if we want to inject dependencies such as an instance

of a service, we need an explicit constructor.

Since the constructor function is executed when the component is created, it is primarily used for initialization and not for

code that has side effects or takes time to execute.

Using Lifecycle Hooks

Angular creates the component, renders it, creates and renders its children, processes changes when its data-bound

properties change, and then destroys it before removing its template from the DOM.

A lifecycle hook is an interface provided by Angular.

OnInit lifecycle: perform any component initialization after Angular has initialized the data-bound properties. This is a good

place to retrieve the data for the template from a back-end service

OnChanges lifecycle hook: perform any action after Angular sets data-bound input properties.

OnDestroy lifecycle hook: perform any cleanup before Angular destroys the component.

Getters and Setters

In JavaScript - two ways to define a property in a class (declare simple variable for a property or use JavaScript getter and

setter)

private keyword - backing variable is private and should only be managed by the getter and setter.

Arrow function: compact syntax for defining a function


Template variables: input and output

Tree shaking process whereby the Angular compiler shakes out unused code for smaller deployed bundles.

Observable sequence (Observable stream/ Observable): collection of items over time.

Next: occurs when next item is emitted and provides the emitted item

Error: occurs when error and provides the error information

Complete: Observable completes and no more items are emitted

HTTP service - allows to communicate with a back-end web server using the HTTP request and response protocol

get method of HttpClient service, which returns an observable.

On subscribe to observable, the HttpClient service sends a get request to the web server.

The web server response is returned to the HttpClient service, and the observable emits the next notification, providing

the response.

observables pipe method - specify a set of operators

tap operator - access emitted item without modifying it

JSON.stringify - JavaScript method that converts an object or array of objects to a JSON string.

Angular first initializes the component and executes the ngOnInit method.

getProducts method of the productService.

The productService returns an observable of IProduct array.

subscribe to that observable and the HTTP GET request is submitted


Callbacks
Promises: are composable - put together several promises that each represent a call to a web server and then execute

some code only after all of the web server calls have returned with their data, not just after the first one.

Observables: actually deal with streams of data

BehaviorSubject: has next function on it - allows to stick new values into our observable

The BehaviorSubject has the next function on it, and that allows us to stick new values into our observable. The

observables that we get from Angular when we use HTTP don't have this next function. When we get the data back from

the HTTP, we don't need to add more data. We're just going to process that data. But when we want to create our own

observable, usually we use a BehaviorSubject, and we can add new values into it using the next function. And so when

we do that, it's going to print out one because it's going to go back to the code in the subscribe, and it's going to execute

that code. And if we then call next and pass in a 2, then of course, that's going to, once again, call the subscribe function's

callback value, and that will print out a 2.

Routing

Snapshot: component only needs to read the route parameter one time - snapshot to access the paramMap and get the

parameter. The snapshot gives us route information at a single point in time. We use this technique when the route

doesn't change while displaying the component. For the ProductDetailComponent, the route parameter defines the

product that the component displays. That parameter doesn't change while displaying the component. To change the

viewed product, the user must leave the product detail page and pick another product from the product list page. If the

component needs to redraw parameters as they change, we use the paramMap observable. Recall from earlier in this

course that an observable is a collection of items that occur over time. We subscribe to the observable to receive

notifications every time the parameters change. If our product detail component had next and previous buttons, the route

could change without leaving the product detail page. Then we'd use the observable to respond every time the route

parameters changed.
RouterModule registers the Router service provider, declares the router directives, and exposes our configured routes. Do

not register a service more than once - forRoot to pass in our configured routes, the RouterModule knows to register the

Router service provider.

forChild - the RouterModule knows not to reregister the Router service

Mobile and Native Frameworks

In today's day and age, most websites receive more views from phones than from desktop computers, so being able to

set up and offer a mobile application can really set you apart from your competition. But mobile apps are expensive to

build, especially since you may need to build them two or three different times for each of the different phone OSs, or you

may want to build a desktop application. With Angular, you can do all of this, and we're not going to really talk too much

about the pros and cons of these tools, just more about their existence. For mobile applications, although there are quite a

few options, some of them are more low-level than others, and there are basically two tools that are commonly used with

Angular to build native mobile apps, these are Ionic and NativeScript. Ionic has been around for much longer and has a lot

more popularity, but NativeScript, built by Telerik, is a close second. For native desktop applications, Electron has become

the de facto option, which allows you to create cross-platform desktop apps in Angular or any other JavaScript framework.

It's a great tool and it's even used to build Visual Studio Code, one of the most popular coding editors. With these and

other tools, you can create native mobile and desktop apps with Angular and save yourself months and even years of

development time.

Testing Tools

Testing is an important topic for any framework. The benefits of testing are well supported by both consensus and study,

so any framework you use should readily support testing. Angular definitely falls in this category. There are several testing
tools that are either available separately or provided with Angular. The Angular team built two testing tools. The first is

Karma, a unit testing tool. It's installed locally and will run your unit tests against multiple browsers depending on how you

configure it. It's very fast and very convenient. The other tool they built was Protractor, a web automation testing tool built

on top of Selenium for running end-to-end tests. Sadly, Protractor has been end of lifed, and the Angular team will no

longer support it or produce new versions of it so you don't want to use it on future projects. Now these tools have been

around for a while, but they do have some competition. For Karma, the main competitor is Jest. There are some other less

popular competitors as well. For Protractor, there is Cypress and Playwright. In addition to these other tools, Angular itself

comes with some tools that will help out with testing. First, there is the TestBed. This is a useful library for when you want

to test components with their templates. The TestBed helps you construct components in a small live Angular

environment and gives you handles to wrappers around the component and the document object model created by its

template. Then there is the async and fakeAsync utilities. These utilities take advantage of zone.js to allow you to run

asynchronous code as if it were synchronous. For testing asynchronous code, this is incredibly helpful. And finally, is the

MockBackend, which can help you to when testing components or services which make HTTP calls. The MockBackend

utility allows you to mock out an HTTP server to respond to HTTP calls during a test and test that they happen the way

that you wanted. And just as a note, since everything in Angular is just a JavaScript class, you can always just test the

code using plain old JavaScript testing techniques with no need for additional help or utilities. With all these testing tools,

Angular's testing story is straightforward and fully featured.

The AOT Compiler

Angular's ahead-of-time compiler is one of its key innovations. It allows for amazing performance in your application.

Without an ahead-of-time compiler, when a client-side rendered framework needs to run, it not only has to download the

code and templates you write and the utilities that you use in that code, it also has to download a compiler to render your

code and templates into actual views. The AOT compiler does this step at compile time so that this major piece of the

framework doesn't need to be sent down to the browser saving downloaded bytes and the time spent compiling your

code.

Editors
Editors are the most commonly used tool when developing an Angular application. Giving an editor more power to help

you create your web apps faster and easier is one of the benefits of using Angular. There are two main ways that an

editor can give you additional features when using Angular. The first is TypeScript. Now again, you can use TypeScript

with other front end frameworks, so this is by no means unique to Angular, but since TypeScript is required for Angular,

it's worth listing here because with Angular, you will definitely receive these benefits and that requirement means the team

actually builds features directly into Angular that will benefit it's close-tied TypeScript. TypeScript gives you two main

benefits. First, since you can get the type of an object, you can know its interface. This gives you better IntelliSense. For

classes and objects, the editor can prompt you with the correct properties and methods, and for prototypes, it can prompt

you with all the usual properties and methods of those as well. The other main benefit of TypeScript is catching

type-related bugs. Although not in complete consensus, studies have shown that this can prevent a very meaningful

number of bugs in an application. And then there is the Angular Language Service. This is an additional tool built by the

Angular team that provides similar functionality to that of a typing tool like TypeScript, but it does it in your templates

where there isn't a language per se, just your bindings This way, you can get auto complete, as well as IntelliSense for the

binding code in your templates. The Angular Language Service has been adapted to be used in Visual Studio Code,

WebStorm, and other editors as well.

Signals

It's difficult to adequately describe how exciting signals are. In order to understand why they're so cool, we have to

understand the difficulty of change detection. So here's a simple representation of how Angular or really any other

front-end framework would help you to display three pieces of information on a page. As you can see, we have quantity,

unitPrice, and totalPrice. TotalPrice, of which is the combination of quantity and unitPrice multiplied together. The first

thing that needs to be done is that these three values in your JavaScript need to be turned into HTML. The first time we

do that, that's no problem. Angular just goes through the HTML, looks for your little binding directives that we can see

here little excerpts of, and then turns that into the HTML where you specify it in the page. But now, what happens when

one of these values changes? Well, we need to have Angular re-render that data. So first, Angular needs to know that

something has changed. So that's what the change detection process is for. Right now, that runs every time that Zone.js

tells Angular that something has happened. But Angular doesn't know what, if anything, has changed, so it has two

options. Either re-render everything, which is a very slow process, especially if you have a large complex page or try to

keep track of what the old values were, then look and see if those values have changed. And if so, then re-render them.

As you can imagine, keeping track of all the old values means that Angular has to do a bunch of internal housekeeping.

This also leads to problems. And our example here has the additional complexity because totalPrice is based on quantity

and unitPrice. So if quantity changes, we need to not only re-render quantity, we need to re-render totalPrice. And here

we're only looking at simple, primitive numeric values, which are easy to track and easy to see if they've changed. But
what if we're talking about an array of hundreds of items, say a list of users or stock prices, and just one of those pieces of

data changes? Comparing the old list to the new list is also a computationally expensive process. So the ideal situation for

performance and predictability is for us to tell Angular when something has changed and what. But that usually means a

lot of complex, error-prone methods for changing data. Enter signals. A signal represents a value of some kind, either a

simple primitive value or something as complex as a list of objects. To create a signal, we just invoke the signal method,

and we give it an initial value. If we want to get the value of a signal, we call the signal like a method. To change the

value, we can call the set method on the signal. To change the value based on the existing value, we can call the update

method. And we can create derived signals based on other signals by creating what's called a computed signal. The

beauty of all of these things is that under the hood, they're communicating with Angular, and they let Angular know

whenever something is changed, and what exactly has changed. So now, just by working with our data in this manner,

we're communicating with an Angular, telling it how and when to re-render any changed values. This makes Angular so

much faster and easier to use with large, complex applications. I highly recommend you learn more about signals and use

them in your Angular applications.

dev server's job is to send code down to the browser. And if we change that code, the dev server that we have launched

by running npm start will send the updated code down to the browser and refresh the browser for us

Proxy is a configuration setting in our Angular application that it uses in order to determine where certain requests will go

browser loads entire application into its memory or at least large parts of the application at a time and simply displays the

portion of the application that matches the URL.


‘name’ attribute - ngModel uses that attribute internally

System should create the services that will ultimately be injected into components and other services.

A dependency provider configures an injector with a DI token, which that injector uses to provide the runtime version of a

dependency value.

factory function - function executed to create a new DataService instance

By writing a custom function rather than just letting Angular use the new key word to instantiate an instance, I have more

control over how it gets created.

New dataService instance with the new keyword and passes it the LoggerService instance that was passed to the factory

function.

Service to a module by adding it to the providers array inside the ng module decorator or by specifying root for the

providedIn property on the injectable decorator, the service will be added to the root injector and be made available to the

entire application.

Providing a service in a lazy loaded module - create a new child injector for that service

Same service to two different injectors - create two separate instances of the service. Which instance is delivered to a

constructor depends on where the requesting component falls in the hierarchy relative to the two instances

observables – RxJS

promises - ES2015 version of JavaScript


pipe method - place to handle any errors that get returned from the server and send my new custom error type back to the

component

catchError operator - takes a function as a parameter

Functions that contain code that returns a promise are declared with the async keyword.

await keyword in front of the call that returns a promise. Function declared with async keyword will return immediately so

that the app remains responsive.

However, rather than registering callbacks, the code inside the async function will pause on the line with the await

keyword while the asynchronous work is performed. Execution will continue linearly when the return promise is resolved

or rejected.

runtime bundle: webpack runtime - application's going to load all of our modules and put everything together for us

main bundle: core of code and the root NgModule

polyfill bundle: polypill for different browsers

styles bundle: all the styles be located

vendor bundle: contain Angular and any other third-party vendor files that we pull into the packages

production build is putting together but what's launching this server is a development server.

When live in production - run on some kind of a CDN or using Node Express or any web server technology
things we can do with Routes:

multiple routes

pass data to routes

preload data for our views

group our routes

guard our routes

add styling and animation

improve performance by asynchronously loading our routes

You might also like