Angular
Architecture of Angular App
(framework/platform written HTML/TypeScript). Functionality of app written in TS files > imported throughout the app as libraries, adding functionality throughout app. TS files transpiled into JS by Angular CLI. Then bundled a bundled payload delivered to the browser
Shared Modules
- a container of all the components you know have to be reusable ie. w/ Material UI we import the Material module into our own modules to get access to its UI components.
TypeScript
-(Built by Microsoft) Superset of JS. provides: type interfaces. Static typing Bugs Found @ compile time Longer compilation time due to extra step to transform TS into JS.
History of Angular
-AngularJS released May 2011 - Angular 2 released (complete rewrite of AngularJS) (Written in TypeScript, mobile oriented kept in mind, use of JavaScript ES5/ES6) -Angular 3 skipped (version mismatch between @angular/core, @angular/compiler and @angular/router libraries) -Versions 4+ released up to Angular 11 (current version)
Angular Code Best Practices
-Component-based architecture -Modularised structure -Dependency injection -Testing -Readable code -Ease of maintenance
Why use Angular?
-Cross-Platform Framework (desktop, mobile,web) -Google LTS -Built on TypeScript -Angular CLI -Built on Code Best Practices -Testing -Ideal for Enterprise lvl Apps -Large Angular Community -3rd party Apps
Example @Output/EventEmitter for Parent Component
-In the parent, we've created an event handler called receiveMessageFromChild($event), which takes in a $event object. -In the template, you can see that when messageEvent from the child is fired, the receiveMessageFromChild($event) handler is fired.
Example String Interpolation in Action
-In this simple component, we have an inline template that is using the {{ }} brackets to display the name property. -Component class, we defined the name property, and -then in the ngOnInit() life cycle hook we set the value of this.name to 'Interpolation is weird'. Here, we can see that one-way data binding is where the name property has been defined. -Then, in ngOnInit(), we set the property. -Angular then triggers an update on the text that's displayed in the view by setting the property's value and sending this update one-way to the view.
Angular App as a Tree
-Module is the trunk of the tree, -Components are the branches of the tree, branching out of the module, with services being passed into components to share data throughout the application. --Everything is tied together through the module, and as the complexity of the app grows, the number of modules in the app will grow.
Three main parts of Angular App
-Modules -Components -Services
Observables/Subscribing
-Observable has certain properties and methods that allow it to open a connection to another data source (ex. API or an event on a button). -The Observable watches the data source, then when something happens on the data sources end, an API returns some data, and the observable reacts to this return of data and performs an action. -it subscribes to this data source. It basically says, 'I am interested in the data or action you return, so I'm going to listen for you to return the data and when I hear that, I'll perform an action'
Create and Add Service
-Step 1: Create service using CLI command -Step 2: Add service to app.module.ts file (add to providers array) -Step 3: Add service to app.component.ts file (add service to constructor of component class)
Two Main Parts of Components
-The @Component decorator -The component class.
Example @Output/EventEmitter for Child Component
-To create messageEvent in the child component, we're using the @Output() decorator to define an output, which is sent using EventEmitter. -The <string> part of EventEmitter is saying that the message/data being passed in the event should be a type of string. (This is another way TypeScript does type checking.) Output is: I don't want to tidy my room
@Output decorator and EventEmitter class
-data passed from the child component to the parent. -involves defining events that can be subscribed to. -Child defines what events it emits -Parent listens for these events, which can contain data. -ideal for notifying parent of button clicks or changed form fields within child component.
Benefits of Dependency Injection
-follow the principle of single-responsibility -we can take individual elements/objects and test them in isolation -(Separation of Concerns)-each part of an application is not aware of other parts of the application
providedIn with Bundling in Angular
-previous versions, tree shaking was not a feature, there was a one-way connection between the services being injected and the providers. -The provider contained a list of the services within the module, and the service did not know what module it belonged to. -Now w/ providedIn property, the service also knows what module it belongs to. -the module no longer needs to know of all the dependencies, and therefore when the application is running, the unused dependencies (services and so on) can be removed.
Two Main Folder to Angular App
-src (contains all the source code for your app) -e2e (contains all your end-to-end tests)
MVC Pattern and Component Class
-the template HTML file is the view --our objects are the model, -and the Component class is the controller (central point connecting view and model).
One Option of using a Service
1.) DataService injected in constructor of component 2.) calling DataService's getMessage() function to set component's message prop to value in DataService.
Angular Material
A UI library that provides a set of modern UI components that work across the web, mobile, and desktop. Allows you to build Angular applications that are designed to look exactly like native mobile applications
CLI Builders
API that allows us to add to and build upon features w/ the Angular CLI. Allows us to write cmds that can change the build system of Angular. Ie. have all our Angular Libraries Built at the same time.
The LifeCycle of Angular Components
All components go through the same life cycle: 1.) Angular creates the component, renders it, 2.) then creates and renders any child components. 3.) Angular also handle changes in data properties within our component and when a component is removed from the view, for example, when navigating to a new view.
Life cycle Hooks
All of these stages have life cycle hooks we can tap into and add our own logic to so that we can have our application do something while a component is going through one of these stages.
ng Build
Angular CLI Cmd that generates a release version of the app. The release version can be hosted on your live server for clients to access. Builds a new dist folder.
Different Types of Injectors used by Angular Dependency Injection Framework
Angular employs hierarchical system when using different injectors. Different types create certain levels of isolation. ie. @Component Injector injects a service at component level or only available at a certain module level. Results in creating specialized services that perform one task, needed in only one place
Search for the Class being injected
Angular uses hierarchy to search codebase for referenced classes @Component operator provides list of classes component needs to be provided with. @Injectable set at the root level (module) with the providedIn prop. But can change to limit to a certain module for ex. @Module: classes available at module level
@Component Decorator
Contains 3 parts: -The selector -The template URL -The styles URL
Example Parent Component of Parent > Parent
Here, we are using an inline template, which has the child component's tag passing the parentMessage property to the child component via the messageForChild property.
Provider Token
In ClientModule, we can see how ClientService is itself being used as this token. Here, ClientService is the token that is being provided to the providers array.
Example Parent Component of Parent > Child
In this example code you can see that we've set the @Input() decorator on the messageForChild property. Now, this property is recognized by Angular as a way to pass properties into the child component. Output Will Be: Say Tidy your room
Input and Output Decorators
Nested Components communicate w/ their container components using @Input/@Output bindings.
Observable Implementation
Observable is an object that provides support for sending messages from publishers to subscribers within an application.
Parent/Child vs. Child/Parent which is a better approach?
Parent/Child: tighter cohesion between the parent and child since child is ref within parent. Child/Parent: child sends out events that parent or other components can listen for leading to Separation of Concerns and flexibility for code refactoring **Both approaches result in one-way data flow.
SPA Pros/Cons
Pros: No full page reloads = performance gains and more dynamic user exp. Cons: SEO hit More effort to maintain state Implement Nav Meaning Performance Monitoring
App Module
Root module in Angular App. Bootstraps the app on launch. -The declarations array -The imports array -The providers array -The bootstrap array - (Exports Array shown in other Modules vs App Module)
Angular Loading Services into Components
Services have a single responsibility Angular loads services into components through Dependency Injection.
Services
TS classes used to access information and share it between multiple components.
Modules
TS files that are containers comprised of components. Help structure and group the functionality of our application.)
Provider
The Injector needs a provider to create the instances (versions) of the classes being injected into all the components, services, and directives. -providers give our application data and access to other modules and components -relationship b/w injector and provider is set up through a token that the injector uses at runtime to create the required class that the provider needs. -When our application is running and a class is needed via Dependency Injection, the token that the provider gives makes sure that the class being used is the one with the correct token.
Providers Array
This contains any services that are required by components. (Can be added at a module level, (available to all components part of that module, or just the component level.)
Imports Array
This contains other modules, whose classes are needed by components of the module they are being imported into.
Singleton design pattern
This means that both components are accessing the same data from the same class.
Template URL
We set what template this Component class uses by defining a URL to the template HTML file. templateUrl: "./app.component.html"
StyleUrls
We then define the CSS file(s) that defines the style for this component. styleUrls: ["./app.component.css"]
Example @ViewChild Decorator in the Child Component
You should see the following in the output: Message: I don't want to tidy my room
Angular
a JS framework used to build client-side web apps that can run on all platforms.
Dependency Injection
a design pattern that allows the creation of dependent objects outside of a class and provides those objects to a class in different ways. The ability of a class to have the other classes it is dependent on injected into itself instead of having to manually create the dependencies.
API endpoint
a reference to a URL that accepts requests.
Web Components
a series of web APIs, which allow you to create your own HTML tags that the browser understands without the need for a third-party JavaScript library or server-side rendering if you used languages like ASP.Net or ColdFusion.
Shared Services (or just called a service)
a way for passing data between unrelated components. @Injectable decorator = service can be injected into other components/services Services load data from external sources and share between components.
@Injectable Decorator
added to a class, this tells Angular the class/functionality can be passed into components/ other services, using D/I
TypeScript Interfaces
allow us to abstract the model of the application into types that our application will use.
Schematics
allow us to apply transforms to our projects; we see an example of this when we ask the Angular CLI to create Components or Services for our App. Essentially its workflow tool that can be run thru the CLI (series of tasks) ie. Generating a Component creates a component class, test class etc.
Provider Object Literal
allow us to give a more relevant name to our services. ie. use name HttpClientService, in our components, instead of HttpClient
Fetch API
allows us to access APIs through a set of objects. -Each object has its own set of methods we can use to access data. ex: WindowOrWorkerGlobalScope.fetch() Headers Request Response
Alternative Class Providers
allows you to use a different class but for the same provider token. Allows us to create a new class without breaking the existing codebase. Our module will work using our new CompanyEmailScheduler class, which extends on the original class. The component that has the original EmailScheduler as a dependency is still going to work.
XMLHttpRequest Interface
an API that uses an object's methods to transfer data from a web server. ex. GET, PUT, POST, DELETE etc.
Factory Providers
approach is ideal for situations when we need to create a provider, but the data it provides may change based on some data we don't have until runtime. Ex. when a user is logged into the application, you need a provider to give you some data that is based on the user's login credentials.
Web Components etc.
are built using standard web technologies (HTML, CSS, and JavaScript).Native to the browser therefore faster to render. By using Web Components, Angular takes advantage of the built-in functionality of the browser, meaning that any application built using Angular is extremely fast. Web components can be rendered w/o 3rd party libraries like Angular. However Angular provides lots of other features for building powerful web apps so Angular makes use of the modular web components.
Components
building blocks of Angular app. Contains a class (business logic) and a view (renders props and methods defined in class)
Angular CLI (Written in Node)
command-line tool. provides us w/ -required dependencies -Boilerplates for webpack and unit test config -transpile TS files into JS -injecting req services
Nested Components
component within another component. (Outside comp = parent, inner comp = child)
BootStrap Arrary
contains main (root) component which starts the whole application. Only the root module in our app (app.module.ts file) can have a bootstrap array.
Declarations Array
contains the components, directives, or pipes that are part of the module. (can only belong to one module unless declared as a Shared Module). Array tells Angular where it can find the tag selectors
Exports Array
contains the list of components, directives, and pipes that can be used by the importing module. By default all the components are private within a module. When listed in exports array, they become declared as public.
Passing data from the child component to the parent component
different ways.: -@ViewChild Decorator -@Output Decorator and EventEmitterClass
Value Providers
give us a way to supply an object instead of an Injector to the Provider. We may use this approach if we want to provide a simple exported function that performs a single task. In this example, we're creating a simple function, then setting it to a variable that is used in an object literal when we set the provider.
Angular Elements
gives us the ability to create custom web components that can be loaded into any modern browser. Thru these Web Components we can create small angular apps which will run as part of the web page. Ie. ASP.NET app but we want a small section of the page to use functionality build in Angular. Angular Elements will convert the Angular app into a web component that will run within the ASP.NET page as a standalone piece of functionality.
Dist folder
has all the compiled JS files of the app and one index.html file. There are no Typescript files and no other HTML files b/c everything has been compiled.
Another Option of using a Service
injecting DataService, 1.) user clicks button from the template 2.) changeMessage() function of DataService is called passing on a new message. 3.) message property in DataService is updated changing the value that is available to our original parent component. **Reason that this data is the same for both components is that the service in Angular is using a singleton design pattern.
HttpInterceptor
intercept all the API requests that your application makes in order to manipulate the request and to ensure that all responses from the API request go through the same process. ie. HTTP Status Error code checking to reroute the user
ngAfterContentInit() Child Hook
invoked after Angular performs content projection into the component's view. Done using ng-content and ContentChild
ngAfterContentChecked() Child Hook
invoked each time the content of the given component has been checked by the change detector
ngAfterViewChecked() Child Hook
invoked each time the view of the given component has been checked by the change detector
ngDoCheck()
invoked when the change detector of the given component is invoked
ngOnInit()
invoked when the component initializes and gets the data
ngOnDestroy()
invoked when the component is destroyed by Angular. Place our cleanup code, unsubscribe from Observables, and clean up event handlers (improve performance).
ngAfterViewInit() Child Hook
invoked when the component's view has been fully initialized
ngOnChanges()
invoked whenever there is any change in the @Input property
Functionality of NgModules
main role is to tell the framework what components belong where when the application is being compiled. groups functionality together allows developers to work on separate parts of an app w/o affecting others work
One Way Data Binding
passing the value of a property in component class to the view when it is updated.
Two ways Modern Browsers Support reaching an API
see photo...
Component Class
see picture
Components etc.
see picture
@ Class Decorator
tells Angular about the details of this module. ex. @NgModule
Ahead of Time Compilation
the ability that Angular has where it can convert our HTML and Typescript into JavaScript before the browser downloads and uses this Javascript.
Selector
the name that's used to create the tag name of the component. selector: 'my-app-root' HTMl Tag: <my-app-root></my-app-root>
Template
the visual part of the component
Services Cont
used to create more modularity and reusability within the app. Each service performs a single piece of app's functionality.
ContentChild
used to get 1st element/directive matching the selector from the content DOM.
Predefined tokens and providers
used when we need to run a piece of code as the Angular framework starts up an application.
@ViewChild Decorator
used when we want to access following inside the component class: -DOM element -Child Component -Directive
HttpClient Service
uses XMLHttpInterface as its backbone, which in turn uses the browser's support of XMLHttpInterface to access external APIs.
Interpolation (string interpolation)
uses one-way data binding to bind the the value of a variable defined in the component class to a UI element. Elements name inside {{ }}
Passing data from the parent component to the child component
using @Input() decorator to pass data from parent (who can manipulate first) to child component via template of child component. Child has no way of getting data. That is the job of the parent.
Example @ViewChild Decorator in the Parent Component
using the @ViewChild() decorator to set the childComp property as the reference to ChildCompComponent. Thus making it and its public properties available to the parent. Then, in the ngAfterViewInit() life cycle hook, we're setting the parent's message property to be the same as the child's message property.
SPAs
web app implementation that loads only a single web doc (index.html), then updates the body content of single doc via JS APIs (AJAX calls using HTTP methods to fetch data, no full page reloads). Data to HTML transformation done on the Client-Side using template engine in SPA-friendly browser results in faster rendering.
Tree Shaking
when app is running, any services that aren't used at the time can be removed from the final bundle of the application. Angular compiler shakes the application to remove all the dead leaves (or services in Angular's case). Creates a smaller download for user = faster app startup time.