• Tidak ada hasil yang ditemukan

Buku Angular 2+ Notes for Professionals

N/A
N/A
gurmel singh

Academic year: 2024

Membagikan "Buku Angular 2+ Notes for Professionals"

Copied!
232
0
0

Teks penuh

This is an unofficial free book designed for educational purposes and is not affiliated with the official Angular 2+ group(s) or companies, nor Stack Overflow. The information presented in this book is not guaranteed to be correct or accurate, use at your own risk.

Getting started with Angular 2+

Getting started with Angular 2 with node.js/expressjs backend (http example included)

Create the package.json (for dependencies) and app.js (for bootstrap) for our node.js application. Just like we did with our backend, our frontend also needs the dependency files.

Install angular2 with angular-cli

The command below will generate a component in the directory you are currently in ng generate component my-generated-component. Module ng g module my-new-module Component ng g component my-new-component Directive ng g directive my-new-directive Pipe ng g pipe my-new-pipe.

Getting started with Angular 2 without angular-cli

Then we create the AppComponent class with title and message variables that we can use in the template. Now we create a main.ts file, which will be the first file that Angular looks at.

Getting through that pesky company proxy

You can also modify AppComponent to use templates, external styles, or add/edit component variables. They can be added to the root of the project (in the same place as package.json or you can put them in %HOMEPATH% and they will be available to all your projects.

Keeping Visual Studios in sync with NPM and NODE Updates

These files probably don't exist yet, so you can create them as empty text files. The part that isn't obvious and is the main reason why people think the proxy settings aren't working is the %5C, the URL encoding of the \ to separate the domain and usernames.

Let's dive into Angular 4!

Components

A simple component

Templates & Styles

Testing a Component

Nesting components

Component interactions

Pass data from parent to child with input binding

The parent component cannot bind data to the child's start and stop methods or to its seconds property. It takes a bit more work to get the child view into the parent component class.

Parent - Child interaction using @Input & @Output properties

There is no actual risk in this application because the lifetime of an Astronaut Component is the same as the lifetime of the application itself. We do not add this guard to the MissionControlComponent because, as a parent, it controls the lifetime of the MissionService.

Parent - Child interaction using ViewChild

We set the click event on each one so we can notify the parent of the page number clicked.

Bidirectional parent-child interaction through a service

Directives

Attribute directive

Component is a directive with template

Structural directives

Custom directive

Copy to Clipboard directive

We need to create a dummy text area with the text to be copied in the DOM var textArea = document.createElement("textarea");. Tell the user that copying is not supported and provide an alternative, e.g. warning window with the text to be copied.

Testing a custom directive

Page title

Templates

Angular 2 Templates

Commonly built-in directives and services

Location Class

AsyncPipe

Displaying current Angular 2 version used in your project

Currency Pipe

Directives & components : @Input @Output

Angular 2 @Input and @Output in a nested component

Input example

Angular 2 @Input with asynchronous data

We use ngOnChanges which fires whenever a component's input changes, check if the data exists and use it if it does. Note that the child template will not indicate if a property that relies on the data being passed is not true.

Attribute directives to aect the value of properties on the host node by

HostBinding

How to Use ngif

To run a function at the start or end of *ngFor loop Using *ngIf

Display a loading message

Show Alert Message on a condition

Use *ngIf with*ngFor

How to use ngfor

Unordered list example

More complext template example

Tracking current interaction example

Angular 2 aliased exported values

Angular - ForLoop

NgFor - Markup For Loop

Angular 2 for-loop

Modules

A simple module

Nesting modules

Pipes

Custom Pipes

Built-in Pipes

Chaining Pipes

Debugging With JsonPipe

Dynamic Pipe

Unwrap async values with async pipe

Stateful Pipes

It is important that your pipe also implements the OnDestroy interface so that you can clean up once your pipe is destroyed.

Creating Custom Pipe

Globally Available Custom Pipe

Extending an Existing Pipe

Testing a pipe

OrderBy Pipe

The Pipe

Angular 2 Custom Validations

Custom validator examples

Using validators in the Formbuilder

Routing

ResolveData

It works the same way for the User Detail Page component: replace data.users with data.user or whatever key is defined in app.routes.ts (see below). IMPORTANT: Services used in the solver must be imported first or you will receive a 'No provider for .Resolver error' message. Please note that these services will be available worldwide and you will no longer need to declare them to the component suppliers.

Routing with Children

Basic Routing

First step is to check if you are pointing to the correct/latest route dependencies in package.json. In a route file (route/routes.ts), enter all the components you need to configure for different route paths. ProviderRouter method is called with RouterConfig as parameter so that it can be injected into the components for calling route-specific tasks.

In your main.ts (Can be any name. basically it should be your main file defined in systemjs.config) import { bootstrap } from '@angular/platform-browser-dynamic';. By default, RouterOutlet will load a component for which an empty path is specified in RouterConfig. The RouterLink directive is used with the html anchor tag to load components attached to routes.

RouterLink uses an array where the first element is the path for routing and the subsequent elements are the dynamic routing parameters.

Child Routes

So by adding the empty route, meaning a route with an empty path, we have defined an entry point for the router.

Routing (3.0.0+)

Controlling Access to or from a Route

This is useful for situations such as waiting for user input to answer a question, waiting to successfully save changes to the server, or waiting to receive data fetched from a remote server.

Add guard to route configuration

Using Resolvers and Guards

Use Guard in app bootstrap

Bootstrapping

Configuring router-outlet

Changing routes (using templates & directives)

Which would require an array called links to exist, so add it to app.ts: public links[].

Setting the Routes

This is especially useful if you have a lot of links, or maybe the links need to be changed constantly. YOU DON'T NEED TO USE '/..' Angular will do this automatic component: The component to load when the route is accessed.

A wrapper component that adds dynamic components declaratively

Dynamically add component on specific event(click)

Rendered dynamically created component array on template HTML in Angular 2

NgModule({ . imports: [ BrowserModule ], . declarations: [ App, ChildComponent ], bootstrap: [ App ], . entryComponents: [ChildComponent] // define the dynamic component here in module.ts.

Installing 3rd party plugins with angular-cli@1.0.0-beta.10

Add 3rd party library that does not have typings

Adding jquery library in angular-cli project

Browse the node_modules and look for files and folders that you want to add to the vendor folder. If you followed the steps correctly, the jQuery library should now work in your project.

Lifecycle Hooks

OnChanges

OnInit

OnDestroy

AfterContentInit

AfterContentChecked

AfterViewInit

AfterViewChecked

DoCheck

Angular RXJS Subjects and Observables with API requests

Wait for multiple requests

Basic request

Encapsulating API requests

A component can now use the BlogApi class to easily retrieve Post data without worrying about the operation of the Http class.

Services and Dependency Injection

Example service

Example with Promise.resolve

Testing a Service

Service Worker

Add Service Worker to our app

Now our application should load faster and we should be able to use the app offline. Now if you enable offline mode in the Chrome console, you should see that our app in http://localhost:4200/index.html works without being connected to the internet. But in http://localhost:4200/ we have a problem and it doesn't load. This is because the static content cache only displays files listed in the manifest.

For example, if the manifest declares a URL of /index.html, requests for /index.html will be answered by the cache, but a request for / or /some/route will go to the network. It reads a route configuration from the manifest and redirects the configured routes to a specified index route. So if we now create either ngsw-manifest.json in the root of the project.

And we build our app again, now when we go to http://localhost:4200/ we should be redirected to http://localhost:4200/index.html.

EventEmitter Service

Catching the event

Live example

Class Component

Class Overview

Emmiting Events

Optimizing rendering using ChangeDetectionStrategy

Default vs OnPush

Angular 2 Forms Update

Angular 2 : Template Driven Forms

Angular 2 Form - Custom Email/Password Validation

Simple Password Change Form with Multi Control Validation

Here we create validators that can be used for the group as a whole: Validators.compose([.

Angular 2 Forms ( Reactive Forms ) with registration form and confirm password validation

Angular 2 - Form Builder

Detecting resize events

A component listening in on the window resize event

Testing ngModel

Basic test

Feature Modules

A Feature Module

Bootstrap Empty module in angular 2

An empty module

Application Root Module

Bootstrapping your module

A module with networking on the web browser

Static bootstrapping with factory classes

Lazy loading a module

Lazy loading example

Advanced Component Examples

Image Picker with Preview

Filter out table values by the input

Bypassing Sanitizing for trusted values

Bypassing Sanitizing with pipes (for code re-use)

Angular 2 Data Driven Forms

Data driven form

Angular 2 In Memory Web API

Setting Up Multiple Test API Routes

Basic Setup

Example of calling a get request for the created API route import {Injectable } from '@angular/core';.

Ahead-of-time (AOT) compilation with Angular 2

Why we need compilation, Flow of events compilation and example?

Using AoT Compilation with Angular CLI

Install Angular 2 dependencies with compiler

Add `angularCompilerOptions` to your `tsconfig.json` file

Run ngc, the angular compiler

Modify `main.ts` file to use NgFactory and static platform browser

CRUD in Angular 2 with Restful API

Read from an Restful API in Angular 2

Use native webcomponents in Angular 2

Include custom elements schema in your module

Use your webcomponent in a template

Update typings

Update typings when: typings WARN deprecated

Mocking @ngrx/Store

Unit Test For Component With Mock Store

Angular 2 - Mock Observable ( service + component )

Observer Mock

Unit Test For Component Spying On Store

Simple Store

Complete example : Login/logout a user

So we'll click a login button and here's what's going to happen: Click the button. Once the HTTP call completes, we'll send another action to alert our store that a user is logged in user.service.ts. As we defined the default state of our reducer in part 3), we will be able to use it like this: user.reducer.ts.

Then we need to handle all actions in our reducer: TIP: Use the ES6 Object.assign function to keep our state immutable. UserComponent: [Dumb component] We just pass the user object from the store using @Input property and async pipe. This way, the component will receive the user only when it is available (and the user will be of type IUser and not of type Observable.

LoginComponent [Smart Component] We inject the store directly into this component and only work on the user as an observable.

Http Interceptor

Using our class instead of Angular's Http

Simple Class Extending angular's Http class

This method checks if any headers have been added, and if not, the header map and ads are 'Content-Type' and 'X-AUTH-TOKEN'. This method, as the name suggests, intercepts the request and checks for any errors. If there is an error it will be checked which error it is and if it is a general it will be handled here otherwise it will be.

Simple HttpClient AuthToken Interceptor (Angular 4.3+)

Animation

Transition between null states

Animating between multiple states

Zone.js

Using NgZone to do multiple HTTP requests before showing the data

Angular 2 Animations

Basic Animation - Transitions an element between two states driven by a model attribute

Sometimes we need to share a component between some apps, and publishing it in npm is one of the best ways to do this. There are some tricks that we need to know to be able to use a normal component like npm package without changing the structure like inlining external styles.

Simplest package

When you install this package using NPM and import it into your application, you just need to pass the package name and your application will learn where to find any EXPORTED components of your package. We used the lib folder because when we compile our code, the output is placed inside the /lib folder. This file is used to configure your npm publish and defines the packages needed to run.

It is used like an html tag . Just install this npm package and load its module in the model you want to use it. src/angular-x-minimal-npm-package.component.ts import {Component} from '@angular/core';. selector: 'angular-x-minimal-npm-package', . styleUrls: ['./angular-x-minimal-npm-package.component.scss'], template-Url: './angular-x-minimal-npm-package.component.html'. This will activate the chain and you will end up with your built in /dist folder and the compiled package in your /lib folder.

This is why in index.js we exported the code from the /lib folder and not from /src. Now all we need to do is publish our package so we can install it via npm.

Angular 2 CanActivate

Angular 2 CanActivate

Angular 2 - Protractor

Angular 2 Protractor - Installation

Testing Navbar routing with Protractor

Example for routes such as /route/subroute for static urls

Basic route example with sub routes tree

Angular 2 Input() output()

Input()

Simple example of Input Properties

Angular-cli

New project with scss/sass as stylesheet

Set yarn as default package manager for @angular/cli

Create empty Angular 2 application with angular-cli

Generating Components, Directives, Pipes and Services

Adding 3rd party libs

Angular 2 Change detection and manual triggering

Basic example

Angular 2 Databinding

Input()

Brute Force Upgrading

Scaolding a New Angular CLI Project

Angular 2 provide external data to App before bootstrap

Via Dependency Injection

Using third party libraries like jQuery in Angular 2

Configuration using angular-cli

Using jQuery in Angular 2.x components

Configuring ASP.net Core application to work with Angular 2 and

Asp.Net Core + Angular 2 + Gulp

Convert bundleconfig.json to gulp file (right click on bundleconfig.json in solution explorer, Bundler&Minifier > Convert to Gulp. You will need: index.html main.ts, systemjsangular-loader.js, systemjs.config.js, tsconfig. json And the app folder.

Seed] Asp.Net Core + Angular 2 + Gulp on Visual Studio 2017

MVC <-> Angular 2

Angular 2 using webpack

Angular 2 webpack setup

Angular material design

Md2Accordion and Md2Collapse

Md2Select

Md2Toast

Md2Datepicker

Md2Tooltip

Dropzone in Angular 2

Dropzone

Basic

Get current state

Add redux chrome tool

Creating an Angular npm library

Minimal module with service class

Barrel

Using Barrel

Testing an Angular 2 App

Setting up testing with Gulp, Webpack, Karma and Jasmine

Installing the Jasmine testing framework

Testing Http Service

Testing Angular Components - Basic

A simple angular-cli command base test coverage

Detailed individual component base graphical test coverage reporting

Debugging Angular 2 TypeScript application using Visual Studio Code

Launch.json setup for you workspace

Basic unit test

Referensi

Dokumen terkait