What is angular?
Angular is a full-featured javascript framework created and maintained by Google and is used for frontend applications or the front-end part of a full-stack application
Angular is very popular in large enterprises.
Planning App
Installing Bootstrap
What you will learn
- Fundamentals of angular
- Components
- Services
- Routing
- HTTP
- Production
Much more
JSON allows us to quickly get a local server up and running
We will setup a server to listen to port 5000
We can customize the data contacts we need
We can set up the data structures that we want our endpoints to return
Angular Components
A component controls a patch of the screen called a view. You define a component's application logic inside a class. The class interacts with the view through an API of properties and methods.
Properties can return data through imported services. Methods will set properties based on user input.
Components are created, updated, and destroyed as a user moves through the application. The app takes action at each moment in its lifecycle through optional lifecycle hooks(ex. ngOnInit()).
For Documentation on Angular components visit: https://angular.io/guide/architecture#components
Angular CLI
documentation
Overview
The Angular CLI is a tool to initialize, develop, scaffold and maintain Angular applications
Getting Started
To install the Angular CLI:
npm install -g @angular/cli
Generating and serving an Angular project via a development server Create and run a new project:
ng new my-project
cd my-project
ng serve
Navigate to http://localhost:4200/. The app will automatically reload if you change any of the source files.
Updating CLI
Npm-Check-Updates
npm-check-updates is a command-line tool that allows you to upgrade your package.json or bower.json dependencies to the latest versions, regardless of existing version constraints.
Installation: npm install -g npm-check-updates
For more info:
documentation
Common commands
Generate a new component, service, or module:
ng generate service
ng generate module
or use shorthand generation commands: ng g c
Run all jasmine tests: ng test
Build/compile the app into an output directory (dist/): ng build
Config
You can use the angular-cli.json file to configure cCSSand javascript libraries like Bootstrap and jQuery.
For example, to use bootstrap you would: npm install bootstrap Then add the following to the styles array in angular-cli.json
"styles": [
"styles.css",
"../node_modules/bootstrap/dist/css/bootstrap.css"
]
Other helpful commands
Search the angular documentation: ng doc 'search term' GitHub angular/angular-cli angular-cli - CLI tool for Angular
Routing
Overview
The browser is a familiar model of application navigation:
Enter a URL in the address bar and the browser navigates to a corresponding page. Click links on the page and the browser navigates to a new page. Click the browser's back and forward buttons and the browser navigates backward and forward through the history of pages you've seen. The Angular Router ("the router") borrows from this model. It can interpret a browser URL as an instruction to navigate to a client-generated view. It can pass optional parameters along to the supporting view component that helps it decide what specific content to present. You can bind the router to links on a page and it will navigate to the appropriate application view when the user clicks a link. You can navigate imperatively when the user clicks a button, selects from a drop box, or in response to some other stimulus from any source. And the router logs activity in the browser's history journal so the back and forward buttons work as well.
Routing
First you need to import the routing package from the angular/router package. ex.... "import { RouterModule, Routes } from '@angular/router';"
Second, you need a base URL of '/' defined in your index.html file:
Your app module is the file that will contain all of your front-end routes, much like your routes file on the back-end. But before we go about defining routes, we have to tell Angular that we are interested in using its optional front-end routing library. To do that, we need to import that library, and in the NgModule decorator's (@NgModule) imports array, specify that our route paths will be constructed on the root ('/' -- our root path that we defined above). Then, remember how routes consist of 1), a URL path and 2), an HTTP verb associated with it? The routes in your app module will similarly have a path, but you'll be loading (i.e., "getting") a component instead. But, remember that if you're loading a component when you hit that URL path, our route will have to know about that component, so you'll have to import that component as well.
import { RouterModule } from '@angular/router'; //tell Angular that you want to use the routing library (it doesn't come with Angular out of the box)
import { PuppiesComponent } from './puppies.component'; //import any components that your routes will be hitting, so that this file knows what we're talking about
@NgModule({
imports: [
..., //other modules
RouterModule.forRoot([ //this function appends the paths below to the base URL we defined in our index.html file above
{
path: 'puppies', //appends 'puppies' to '/' -> '/puppies'
component: PuppiesComponent //So, when we hit /puppies in the URL bar, we will be rendering the PuppiesComponent
}
])
})
When you're defining routes in this manner, start with more specific routes and end with those that are less specific (those that take in route parameters, or, i.e., puppies/edit/:id), because the router uses a first-match wins strategy.
Angular Universal
SEO Optimization: Search engines won't be able to scrape single-page apps; "server-side pre-rendering is a reliable, flexible, and efficient way to ensure that all search engines can access your content." ~Google, Angular Universal Docs
Allows devs to transition from the server view to the client view in the browser.
The best of both worlds: the user experience and high performance of an SPA, combined with the SEO friendliness of a static page.
Terminal
npm install -g universal-cli
Once installed, use ung instead of ng to serve, and generate components, directives, modules, etc.
E.g. ung serve --open
More Angular Universal
The Angular Universal project consists of the base platform API and the surrounding tools tenablebles developers to do server side rendering(or pre-rendering) of Angular applications. The platform API part has been merged into Angular Core as of 4.0.
At a high level, there are two major pieces to the Angular Universal:
Rendering on the server which means generating all the HTML for a page at a given route.
Transitioning from the server view to the client view in the browser client
The basic idea is to build an app that does not just render to the server but also runs on the server. In Angular 2, this is achieved with the help of Angular Universal which loads our app on the server first and then drops it to the browser once ready.
Highlights:
- Better perceived performance
First-time users will instantly see a server-rendered view which greatly improves perceived performance. According to Google research, a difference of just 200 milliseconds in page load performance has an impact on user behavior.
- Optimised for Search Engines
Server-side pre-rendering is a reliable, flexible and efficient way to ensure that all search engines can access your content.
- Site Preview
Ensure that Facebook, Twitter, and all other social media apps correctly display a preview image of your app.
Service worker
a stand-alone javascript program that you can run in your browser. it can handle background/network tasks for your website/web app. service workers allow functionality offline and can speed up your app by using cached files if there has been no change.
place in the index.html file of your app:
in your angular-cli.json add a service worker to your assets:
"assets": [
"assets",
"favicon.ico",
"service-worker.js"
],
The newly updated service worker procedure
For a new project:
- ng new my-project --service-worker
- adds service worker to the whole project (easy mode)
Existing Project:
- step 1: yarn add @@angular/service-worker
- step 2: ng set apps.0.serviceWorker=true
- step 3: import service worker into app.module.ts import { ServiceWorkerModule } from '@angular/service-worker’;
import { environment } from '../environments/environment’;
Then add service worker module to imports in the @NGmodule ServiceWorkerModule.register(newsw-worker.js', {enabled: environment.production})
- Step 4: create a new file called new-config.json. File path src/ngsw-config.json. Add this into the nnewconfig.json file
{
"index": "/index.html",
"assetGroups": [{
"name": "app",
"installMode": "prefetch",
"resources": {
"files": [
"/favicon.ico",
"/index.html"
],
"versionedFiles": [
"/*.bundle.css",
"/*.bundle.js",
"/*.chunk.js"
]
}
}, {
"name": "assets",
"install mode": "lazy",
update model": "prefetch",
"resources": {
"files": [
"/assets/**"
]
}
}]
}
- Step 5: ng serve does not work with service workers. To check if it is working run the following commands in the terminal
- cd dist
- http-server -p 8080
- A service worker is a script that your browser runs in the background, separate from a web page.
- A service worker is a programmable network proxy that lets you control how network requests from your page are handled.
- Service workers only run over HTTPS. Because service workers can intercept network requests and modify responses, "man-in-the-middle" attacks could be very bad.
- Service workers enable applications to control network requests, cache those requests to improve performance, and provide offline access to cached content.
links:
https://www.npmjs.com/package/@angular/service-worker
https://pascalprecht.github.io/slides/angular-and-service-workers/#/a
https://coryrylan.com/blog/fast-offline-angular-apps-with-service-workers
https://angular.io/guide/service-worker-getting-started
TypeScript
TypeScript is a superset of JavaScript that transpires to vanilla JavaScript
Since TypeScript is a superset of JavaScript, any valid JavaScript is also valid TypeScript
TypeScript was developed by and is maintained by Microsoft
Released in 2012
TypeScript adds optional types, classes, and modules to JavaScript
class Person {
private name: string;
private age: number;
private salary: number;
constructor(name: string, age: number, salary: number) {
this.name = name;
this.age = age;
this.salary = salary;
}
It is trantranspiredng the command "tsc"
When transpiles, it makes ES6 features ES5 compatible (which is awesome)
TypeScript is a language for application-scale JavaScript. TypeScript adds optional types, classes, and modules to JavaScript. TypeScript supports tools for large-scale JavaScript applications for any browser, for any host, and on any OS. TypeScript compiles to readable, standards-based JavaScript. Try it out at the playground, and stay up to date via our blog and Twitter account.
TypeScript is a free and open-source programming language developed and maintained by Microsoft. It is a strict syntactical superset of JavaScript and adds optional static typing to the language. Also, check out some other publications we've written
TypeScript can actually report issues without you even saving your file, and leverage the type system to help you write code even faster (which leads to a truly awesome editing experience).
Why Do We Even Use TypeScript?
TypeScript brings several new features to the table. The most notable of these are classes, interfaces, and compile-time type checks. It is better to use TypeScript when:
- You have a large codebase. When more than one person works on a project and the code base is huge, TS will help you avoid common errors.
- Your developers come from strongly typed languages. When developers are already experienced with languages such as C++ and Java and don't want to deal with just JavaScript.
- A framework recommends using TS. Such as Angular 2+.
- You really need that faster performance.
- Angular JS was released in 2010 by Google. It became popular very quickly because of its feature set. Different versions of Angular JS were released like 1.1, 1.2, and so on.
- A few years later, Google engineers completely rewrote the framework to match the needs of today's rich client-side applications. They created a new version of AngularJS in TypeScript (which is not backward compatible) and released Angular 2 as a framework in 2016. They named it Angular 2, removing the JS suffix.
- A few months later, after the release of Angular 2, new features were introduced and various bug fixes were done and the new version was released as Angular 4. There is no Angular 3.
- What happened to Angular 3? The angular codebase is broken into parts/libraries such as core, compiler, animations, router, etc. Each of them can have thown version. RoutThe routerrary reached version 3 and others were still at 2.3. The next version would be 2.4 but having version 2.4 for the router library is incorrect - so to avoid confusion they skipped version 3 and Angular 4 was released. So, when we say Angular it means Angular (2+). When we say AngularJS, it means Angular JS(1.x). See the Angular product website here. http://www.typescriptlang.org/docs/home.html
- NPM documentation for Angular Typescript
//example of basic types let decimal: number = 6; let hex: number = 0xf00d; let binary: number = 0b1010; let octal: number = 0o744; //example of array let numberList: number[] = [1, 2, 3]; //example of an array and any type let list: ay[] = [1, "hello world", false, 1.5]; for(let i = 0; I < lIst.length; i++){ console.log(list[i]); } //tsc is the command to compile ts to js
Angular MODULES
A NgModule is a way to consolidate and organize information like components, directives, pipes, etc. Some examples are the built-in Angular libraries (like FormsModule, HttpModule, RouterModule)... and there are 3rd party modules as well. Modules can also add services to our applications.
Module examples
Every Angular app has at least one module: the root module (app module). You bootstrap that module to launch the application (Angular sets this up for you!)
The BrowserModule includes the directives *ngIf and *ngFor, and luckily it's imported automatically for us when we set up an Angular app
Example of a module import: import { BrowserModule } from '@angular/platform-browser';
"Modules are a great way to provide services for all the module's components." For example, if a module imports and provides a "game-logic-service", then all components within that module can use that service.
Another example: Many applications capture information about the currently logged-in user and make that information accessible through a user service. This service could be provided by a module to all its children components.
Observables && Promises
Promise
A Promise handles a single event when an async operation completes or fails. It is used in preference to callback functions in writing synchronous code. It returns a single value and is not cancellable.
Syntax / Methods
new Promise(resolve, reject) => {}
toPromise();
then();
pending
fulfilled
resolve
rejected
Observable
An Observable is like a Stream and allows you to pass zero or more events where the callback is called for each event. It is cancellable. Uses Reactive Extensions (RxJS). Preferred over promises for Http HTTPests.
How to construct an observable.
Here is an example of how you might create a really simple observable/subscription setup. import {Component} from '@angular/core'; import {Observable} from 'rxjs/Observable';
@Component({ selector: 'app', template: ` Angular Component Using Observables!
VALUES:
ERRORs:
FINISHED:
`
}) export class MyApp {
private data: Observable
constructor() { }
init() { this.data = new Observable(observer => { setTimeout(() => { observer.next(42); }, 1000);
setTimeout(() => {
observer.next(43);
}, 2000);
setTimeout(() => {
observer.complete();
}, 3000);
});
let subscription = this.data.subscribe(
value => this.values.push(value),
error => this.anyErrors = true,
() => this.finished = true
);
}
}
Syntax
Observable provides operators like map, forEach, and reduce, similar to an array
subscribe
unsubscribe
Helpful Resources
- A good article explaining Angular Observables
- Observables are like newsletters that people can subscribe to. for each new subscription, a new newsletter is printed and sent out.
- Another take on Observable diagrams
- When is a promise a better choice?
- Angular Observable Intro
Conclusion
- Both deal with the asynchronous nature of applications but in different ways
- promises return one set value
- observables return multiple values over time
- Promises can be used in most cases, don't wanna overuse observables
- Both push data (initiate from the data creator)
- promises take in data and spit out a value
- observables originate an event and publish it to subscribers
- observables are lazy and only do something when something subscribes to listen to changes
- observables can becanceledd, and promises cannot
SERVICES!
WHAT IS IT? An Angular 2 service is simply a javascript function, along with its associated properties and methods, that can be included (via dependency injection) into Angular 2 components.
INJECTION?
INJECTABLE SERVICES: The @Injectable() decorator tells TypeScript to emit metadata about the service. The metadata specifies that Angular may need to inject other dependencies into this service.
Code Example: @Injectable() export class NameService { }
NAMING CONVENTION: The naming convention for service files is the service name in lowercase followed by .service. For a multi-word service name, use lower dash-case. For example, the filename for SpecialSuperHeroService is special-super-hero.service.ts.
JASMINE/Testing
The Jasmine test framework provides everything needed to write basic tests for Angular. It ships with an HTML test runner that executes tests in the browser.
####Main concepts
Suites?—?describe(string, function) functions, take a title and a function containing one or more specs.
Specs?—?it(string, function) functions, take a title and a function containing one or more expectations.
Expectations?—?are assertions that evaluate to true or false. Basic syntax reads expect(actual).toBe(expected)
Matchers?—?are predefined helpers for common assertions. Eg: toBe(expected), toEqual(expected). Find a complete list here. Note that .toEqual() does a deep comparison while .toBe() is just a reference equality.
Compare Jasmine and Mocha
- Similarities:
- Both uses describe, it, before, beforeeach, each
- Differences:
- Punctuation is different too. Equal vs toEqual
- Jasmine uses ES6 and Mocha uses ES5
- Jasmine opens a new window browser, mocha is just in Terminal
- Jasmine comes with its' own assertion library (which is why it is too. Equal)
- Mocha: expect(num).to.equal(4) Jasmine: expect(num).toEqual(4)
- Use $ng test to run the testing suite
- Helpful links and readings
- Official angular docs
- For end 2 end testing (ie acceptance tests), they use protracto,r not Jasmine. In e2e testing, one process runs the real application and a second process runs protractor tests that simulate user behavior and assert that the application responds in the browser as expected.
- Sample unit test in doghouse
Syntax Example:
describe(‘1st tests’, () => {
it(‘true true, () => expect(true).toBe(true));
});
Karma
ng test - Karma runs all unit test files (based on config file karma.conf.js) in a chrome window (default), watches for changes like ng serve
0 Replies to “Angular Framework Tutorial For Absolute Beginners”
Leave a Reply
Your email address will not be published.