This document was uploaded by user and they confirmed that they have the permission to share
it. If you are author or own the copyright of this book, please report to us by using this DMCA
report form. Report DMCA
INTRODUCTION Angular is a TypeScript-based open-source web application framework led by the Angular Team at Google and by a community of individuals and corporations. Angular is a complete rewrite from the same team that built AngularJS. Angular 2.0+ has a feature of modularity, where a single application is built by separating it in many modules.
WHY IS ANGULAR JS CALLED ANGULAR? Because HTML has Angular brackets and "ng" sounds like "Angular". Because Angular JS can be written inside the angle brackets of HTML that is why it is known as Angular JS .
DIFFERENCES BETWEEN ANGULAR AND ANGULARJS Angular was a complete rewrite of AngularJS. Angular does not have a concept of “scope” or controllers instead, it uses a hierarchy of components as its main architectural concept. Angular has a simpler expression syntax, focusing on “[ ]” for property binding, and “( )” for event binding Mobile development – Desktop development is much easier when mobile performance issues are handled first. Thus, Angular first handles mobile development. Modularity – Angular follows modularity. Similar functionalities are kept together in same modules. This gives Angular a lighter & faster core.
ANGULAR FEATURES
BUILDING BLOCKS OF ANGULAR Modules Components Templates Metadata Data binding Directives Services Dependency injection
NODE JS Node.js is a server-side platform built on Google Chrome's JavaScript Engine (V8 Engine). Node.js was developed by Ryan Dahl in 2009 and its latest version is v0.10.36.
WHY NEED NODE JS? A web browser such as Chrome, Firefox or Internet Explorer understands only Javascript so we have to transpile our Typescript to Javascript and for that we use typescript transpiler which requires NodeJS. NPM (Node Package Manager) comes with node.js by default. NPM allows you to manage your dependencies.
INSTALLATION Go
to, https://nodejs.org/ and download recommended package then install Node JS Go to, https://code.visualstudio.com/ and download windows package then install Go to cmd in visualstudio using ( Ctrl+~) Check Node version in cmd using ( node -v) Check NPM version in cmd using ( npm -v) If it is not available, use ( npm install npm) Now, check NPM version use ( npm -v )
CONT.. Create any folder in any directory: For Ex. Angular in my Local disk D drive. Install the library files globally -> npm install -g @angular/cli Create New project: ng new poroject_name Then select the project: cd poroject_name Now start your project: npm start or ng serve To confirm: Open your browser use this link: http://localhost:4200
MODULE A module is a cohesive block of code with a related set of capabilities which have a specific application domain or a workflow. A module is a mechanism to group components, directives, pipes and services that are related, in such a way that can be combined with other modules to create an application. Any angular module is a class with @NgModule decorator.
DECORATORS Decorators are functions that modify JavaScript classes. Decorators are basically used for attaching metadata to classes so that, it knows the configuration of those classes and how they should work. NgModule is a decorator function that takes metadata object whose properties describe the module.
PROPERTIES OF DECORATORS
declarations: The classes that are related to views and it belong to this module. There are three classes of Angular that can contain view: components, directives and pipes. exports: The classes that should be accessible to the components of other modules. imports: Modules whose classes are needed by the component of this module. providers: Services present in one of the modules which is to be used in the other modules or components. Once a service is included in the providers it becomes accessible in all parts of that application bootstrap: The root component which is the main view of the application. This root module only has this property and it indicates the component that is to be bootstrapped.
MVVM
MODEL A Model is a container defining the structure of an entity, following the object oriented principle. It is defined by your content. So if you want to use a Model for a User, it could look like this. class User { name:string; email:string; address:string; } Note that: Models should not contain any logic. All your logic should be defined in the ViewModel.
VIEW The View is the visual layer of the application, including all visual elements shown on the user’s screen. In the case of Angular 2 the view is defined in a template. These templates are written in HTML and CSS but also contain angular specific elements. These templates a connected to the ViewModel via data-binding. Templates are always part of a component.
VIEWMODEL The ViewModel is an abstract part of the View, managing the models and properties to show on the screen. It contains all the logic for the page. View and ViewModel are often connected via data binding. That means, that changes in the ViewModel, for example on a property, are instantly applied to the view, changing e.g. the text shown on the screen. In angular, the ViewModel is represented by the Typescript part of a component.
COMPONENT Components are the most basic building block of an UI in an Angular application. An Angular application is a tree of Angular components. Angular components are a subset of directives. Unlike directives, components always have a template and only one component can be instantiated per an element in a template.
DATA BINDING Databinding is a powerful feature of Angular. Angular Databinding is used for communication. It is used to communicate between your TypeScript code (your business logic) and the other component (HTML layout). Databinding is necessary because when we write the code in TypeScript, it is compiled to JavaScript and the result is shown on HTML layout. Thus, to show the correct and spontaneous result to the users, a proper communication is necessary.
ONE WAY DATA BINDING In one-way databinding, the value of the Model is used in the View (HTML page) but you can't update Model from the View. Angular Interpolation / String Interpolation, Property Binding, and Event Binding are the example of one-way databinding.
{ { }}
TWO WAY DATA BINDING In two-way databinding, automatic synchronization of data happens between the Model and the View. Here, change is reflected in both components. Whenever you make changes in the Model, it will be reflected in the View and when you make changes in View, it will be reflected in Model. This happens immediately and automatically, ensures that the HTML template and the TypeScript code are updated at all times.
TWO WAY DATA BINDING App.component.ts export class AppComponent { data1: string = '‘”; } App.component.html
{{data1}}
FORMSMODULE(TWO WAY DATABINDING) App.module.ts import { FormsModule } from '@angular/forms'; imports: [ FormsModule ] App.component.html
{{name}}
EVENT BINDING To bind the events along with the methods. This process is known as event binding. Event binding is used with parenthesis (). App.component.ts
TEMPLATE REFERENCE VARIABLE There's another way to get the user data: use Angular template reference variable. These variables provide direct access to an element from within the template. To declare a template reference variable, precede an identifier with a hash (or pound) character (#).
CONT.. App.component.css button{width:50px;} input{width:200px;} App.component.ts data:any=""; result:any; send(x:any) { switch(x) { case 1: this.data+="1"; break; case 2: this.data+="2"; break; case 3: this.data+="3"; break; case 4: this.data+="4"; break; case 5: this.data+="5"; break;
CONT.. case 6: this.data+="6"; case 7: this.data+="7"; case 8: this.data+="8"; case 9: this.data+="9"; case 0: this.data+="0";
break; break; break; break; break;
case "+": this.data+="+"; break; case "-": this.data+="-"; break; case "*": this.data+="*"; break; case "/": this.data+="/"; break; case "=": this.result=eval(this.data); this.data=this.result; break;
case "clr": this.data=""; break; } }
DIRECTIVES The Angular 8 directives are used to manipulate the DOM. By using Angular directives, you can change the appearance, behavior or a layout of a DOM element.
COMPONENT DIRECTIVES Component directives form the main class. It possesses the details about how the component should be instantiated, processed and utilized at runtime.
STRUCTURAL DIRECTIVES As far as a structure directive is concerned, it is associated with manipulating the DOM elements. You will find an asterisk (*) prefix before the directive.
Observables provide the support for passing the messages between publishers(Creator of Observables) and subscribers (User of Observables) in your application. Observables are declarative that is, you define the function for publishing values, but it is not executed until the consumer subscribes to it. The observable can deliver the multiple values of any type like literals, messages, or events, depending on the context. As a publisher, you can create an Observable instance that defines a subscriber function. This is a function that is executed when the consumer calls the subscribe() method.
THREE TYPES OF NOTIFICATIONS next: Required. The handler for each delivered value called zero or more times after execution starts. error: Optional. The handler for error notification. An error halts execution of the observable instance. complete: Optional. The handler for the execution-complete notification. Delayed values can continue to be delivered to the next handler after execution is complete.
SUBSCRIBING ANGULAR OBSERVABLES You can subscribe the observables by calling the subscribe() method of the instance and passing an observer object to receive the notifications. myObservable.subscribe( x => console.log('Observer got a next value: ' + x), err => console.error('Observer got an error: ' + err), () => console.log('Observer got a complete notification') ); Use the Observables constructor to create an observable stream of any type. const obs = new Observable();
CONT.. Create a service and model file ng g s student --spec=false (student.service.ts file inside the src >> app folder) Student.model.ts export class Student { id: Number; name: String; EnrollmentNumber: Number; College: String; University: String; }
CONT.. import { Observable } from 'rxjs'; in student.services.ts We need to create one function inside the service that will return that data in the form of observable. public getStudents(): any { const studentsObservable = new Observable( observer => { setTimeout( () => { observer.next(this.students); }, 1000); }); return studentsObservable; }
HTTP SERVICE Most front-end applications communicate with backend services over the HTTP protocol. Modern browsers support two different APIs for making HTTP requests: XMLHttpRequest interface and the fetch() API. The HttpClient in @angular/common/http offers a simplified client HTTP API for Angular applications that rests on the XMLHttpRequest interface exposed by browsers.
MODEL import { HttpClientModule } from '@angular/common/http'; in
app.module.ts and add HttpClientModule in imports[] User.model.ts export class User { userId:number; id:number; title:string; body:string;
}
CONT.. Basic.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from "@angular/common/http"; import {User} from './user.model'; @Injectable({ providedIn: 'root' }) export class BasicService { apiUrl:any='https://jsonplaceholder.typicode.com/posts'; constructor( private http:HttpClient) { } getData() { return this.http.get<User[]>(this.apiUrl); } }
CONT.. App.component.ts import { Component } from '@angular/core'; import{BasicService} from './basic.service'; import {User} from './user.model'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { users:User[]; constructor(private bs:BasicService) {} ngOnInit()
Note: import { HttpClientModule } from '@angular/common/http'; import { EmployeeService } from './service/employee.service'; in app.module.ts and include in providers[EmployeeService] and Imports[HttpClientModule] as usual…
COMPONENTS
Generate componets App/ ng g c add-emp App/ ng g c edit-emp App/ ng g c list-emp Import components in app-routing.module.ts And write a coding for routing
Angular provides two different approaches for managing the user input through the forms. Reactive approach Template-driven approach Both reactive and template-driven forms share underlying common building blocks which are the following. FormControl: It tracks the value and validation status of the individual form control. FormGroup: It tracks the same values and status for the collection of form controls. FormArray:It tracks the same values and status for the array of the form controls. ControlValueAccessor: It creates the bridge between Angular FormControl instances and native DOM elements.
REACTIVE FORM VALIDATIONS import { ReactiveFormsModule } from '@angular/forms'; and include it in imports[] in app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { ReactiveFormsModule } from '@angular/forms'; @NgModule({ declarations: [ AppComponent, ], imports: [ BrowserModule, AppRoutingModule, ReactiveFormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule {
}
CONT.. App.component.ts import { Component } from '@angular/core'; import { FormGroup, FormControl, Validators } from '@angular/forms'; @Component({