Angular 8

  • Uploaded by: Guhan Ganesan
  • 0
  • 0
  • January 2021
  • PDF

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


Overview

Download & View Angular 8 as PDF for free.

More details

  • Words: 4,068
  • Pages: 98
Loading documents preview...
PREPARED BY GUHAN GANESAN M.E.,

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. 

ADD CSS BOOTSTRAP npm install bootstrap@4 jquery –save  Add url in angular.json "styles": [ "src/styles.scss", "node_modules/bootstrap/dist/css/bootstrap.min.c ss" ], 

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. 

CLASSIFICATION OF DATA BINDING

INTERPOLATION BINDING 

App.component.ts



App.component.html

export class AppComponent {

<strong>{{firstname}}

firstname: string = "Sachin";

<strong>{{lastname}}

lastname:string = "Tendulkar" }

PROPERTY 

BINDING

App.component.ts

export class AppComponent { firstname: string = "Sachin"; lastname:string = "Tendulkar" }



App.component.html

<span [innerHTML]='firstname'>

PROPERTY 

BINDING

App.component.ts

export class AppComponent { firstname: string = "Sachin"; lastname:string = "Tendulkar" }



App.component.html

<span [innerHTML]='firstname'>

ATTRIBUTE BINDING App.component.ts colSpanValue:number=2;

App.component.html
td1


CLASS BINDING App.component.css



.myclass { text-align: left; color:blue; }

Student Details


STYLE BINDING

{{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 

msg:string="Hi"; myEvent() { this.msg="Bye"; }

App.component.html

{{msg}}



CONT.. App.component.ts

msg1:string=""; myEvent1( x: any) { //console.log(x); //this.msg1+=x.target.value+"--"; //(event.target).value this.msg1+=(x.target).value+"--"; } App.component.html

{{msg1}}



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.html Ex1:

{{test.value}}

Ex2: App.component.html

{{msg3}}

App.component.ts msg3:string=""; onEnter(y:any) { this.msg3=y; }

CALCULATOR DESIGNING App.component.html



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. 

TYPES OF DIRECTIVES Component Directives  Structural Directives  Attribute Directives 

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. 

NGIF DIRECTIVES App.component.html

{{msg4}}

{{msg4}}



{{"Welcome"}}
App.component.ts B1:boolean=false;

msg4:string=""; myFun1() { this.b1=true; this.msg4="Hello";

NGFOR DIRECTIVE App.component.ts export class AppComponent { bks:Books[]=[ {id:1001,title:"Tamil",author:"Raja"}, {id:1002,title:"English",author:"Guhan"}, {id:1003,title:"Science",author:"Ramesh"}

] } class Books { title:string; author:string; id:number; }

CONT.. App.component.html
IdTitleAuthor
{{data.id}} {{data.title}} {{data.author}}


NGSWITCH DIRECTIVES App.component.html <select [(ngModel)]="myValue">
  • {{"Chennai"}}
  • {{"Madurai"}}
  • {{"Trichy"}}


CUSTOM DIRECTIVE 

ng generate directive mydirective

CREATE src/app/mydirective.directive.spec.ts (244 bytes)  CREATE src/app/mydirective.directive.ts (151 bytes)  UPDATE src/app/app.module.ts (544 bytes) 

CONT..

Mydirective.directive.ts import { Directive, ElementRef } from '@angular/core'; @Directive({ selector: '[appMydirective]' }) export class MydirectiveDirective { constructor(el:ElementRef) { el.nativeElement.style.color="blue"; }

} App.component.html

Welcome!!!



HOSTLISTENER App.component.html

import { Directive, ElementRef, HostListener } from '@angular/core'; @Directive({ selector: '[appMydirective]' }) export class MydirectiveDirective { constructor(private el:ElementRef) { //el.nativeElement.style.color="blue"; } @HostListener('mouseenter') onMouseEnter() { this.applyMyCss("red"); } @HostListener('mouseleave') onMouseLeave() { this.applyMyCss("green"); } applyMyCss(x:string) { this.el.nativeElement.style.color=x; }

}

ROUTING 

Cmd: ng generate module app-routing --flat --module=app



--flat puts the file in src/app instead of its own folder.



--module=app tells the CLI to register it in the imports array of the AppModule.

By using selector

App-routing.module.ts import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; const routes: Routes = []; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }

GENERATE NEW COMPONENT ng g c home  ng g c about  ng g c profile 

src/app/app-routing.module.ts 

import {HomeComponent} from './home/home.component';



import {AboutComponent} from './about/about.component';



import {ProfileComponent} from './profile/profile.component';

ROUTES ARRAY import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import {HomeComponent} from './home/home.component'; import {AboutComponent} from './about/about.component'; import {ProfileComponent} from './profile/profile.component'; const routes: Routes = [ { path: 'home', component: HomeComponent }, { path: 'about', component: AboutComponent }, { path: 'profile', component: ProfileComponent } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }

CONT.. App.component.html Home About Profile



FOR CHILD ROUTING E:\Angular\myapp\src\app\home>ng g c create  ng g c update  Ng g c view 

Home.component.html

Home



CONT.. app-routing.module.ts import { CreateComponent } from './home/create/create.component'; import { UpdateComponent } from './home/update/update.component'; import { ViewComponent } from './home/view/view.component'; const routes: Routes = [ { path: 'home', component: HomeComponent, children:[ {path: 'create', component: CreateComponent}, {path: 'update', component: UpdateComponent}, {path: 'view', component: ViewComponent}, ] }, { path: 'about', component: AboutComponent }, { path: 'profile', component: ProfileComponent } ];

PIPES The pipe takes the data as input and transforms it the desired output.

App.component.ts mydate=new Date(); arr:any=['a','b','c','d','e','f','g','h','i']; jsonval = {name: 'Anbu', age: '27', address:{no: '12/A', street: 'North Street'}}

App.component.html

{{"uppercase pipes" | uppercase}}

{{"lowercase pipes" | lowercase}}

{{ mydate | date:'d/M/y'}}

{{5786.76578677876 | number:'3.5'}}

{{00.54565 | percent}}

{{arr | slice:3:7}}

{{jsonval | json }}



CUSTOM PIPES Create mypipe.pipe.ts in app folder(component) import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name:'sqr' }) export class MyPipe implements PipeTransform { transform(x:any) { return x*x; }

}

CONT.. Import mypipe.pipe.ts in app.module.ts  import {MyPipe} from './mypipe.pipe';  declarations: [ MyPipe ] App.component.html

{{12 | sqr }}



SERVICE  

To access methods and properties across other components in the entire project. Run ng g service myservice in app component

Myservice.service.ts import { Injectable } from '@angular/core';

@Injectable({ providedIn: 'root' }) export class MyserviceService { constructor() { } }

CONT.. import {MyserviceService} from './myservice.service'; in App.module.ts  Include in providers: [MyserviceService], 

CONT import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class MyserviceService { constructor() { } std:Student[] =[ {name:"Raja",age:28,email:"[email protected]"}, {name:"Anbu",age:27,email:"[email protected]"}, {name:"Ramesh",age:29,email:"[email protected]"} ] send() { console.log(this.std); }

} class Student { name:string; age:number; email:string; }

CONT.. App.component.ts import { Component } from '@angular/core'; import {MyserviceService} from './myservice.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { constructor(private obj:MyserviceService) { } ngOnInit() { this.obj.send(); } }

OBSERVABLES 







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 model file in service file and add demo data import { Injectable } from '@angular/core'; import { Student } from './student.model'; @Injectable({ providedIn: 'root' }) export class StudentService { students: Student[] = [ { id: 1, name: 'Krunal', enrollmentnumber: 110470116021, college: 'VVP Engineering College', university: 'GTU' }, { id: 2, name: 'Rushabh', enrollmentnumber: 110470116023, college: 'VVP Engineering College', university: 'GTU' }, { id: 3, name: 'Ankit', enrollmentnumber: 110470116022, college: 'VVP Engineering College', university: 'GTU' } ]; constructor() { } }

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; } 

DEFINE THE SUBSCRIBER import { Component, OnInit } from '@angular/core'; import { Student } from './student.model'; import { StudentService } from './student.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { students: Student[] = []; constructor(private studentservice: StudentService) {} ngOnInit() { const studentsObservable = this.studentservice.getStudents(); studentsObservable.subscribe( (studentsData: Student[]) => { this.students = studentsData; } ); } }

DISPLAY THE DATA

Observable

{{ student.name }}
{{ student.EnrollmentNumber}}

{{ student.College }}

{{ student.University }}

Go somewhere


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()

{ this.bs.getData().subscribe(data=>this.users=data); } }

CONT.. App.component.html

Id IserIdTitleBody
{{item.id}} {{item.userId}} {{item.title}} {{item.body}}


ANGULAR CRUD Create a model in app/model/employee.model.ts export class Employee { id?: number; employee_name?: string; employee_salary?: number; employee_age?: number; } 

HTTP SERVICES Create app/service/employee.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Employee } from '../model/employee.model'; 

@Injectable({ providedIn: 'root' }) export class EmployeeService { constructor(private http: HttpClient) { } baseUrl = 'http://localhost:3000/employees/'; getEmployees() { return this.http.get<Employee[]>(this.baseUrl); }

deleteEmployees(id: number) { return this.http.delete<Employee[]>(this.baseUrl + id); } createUser(employee: Employee) { return this.http.post(this.baseUrl, employee); } getEmployeeById(id: number) { return this.http.get<Employee>(this.baseUrl + id); } updateEmployee(employee: Employee) { return this.http.put(this.baseUrl + employee.id, employee); }

}

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

export const routes: Routes = [ { path: '', component: ListEmpComponent, pathMatch: 'full' }, { path: 'list-emp', component: ListEmpComponent }, { path: 'add-emp', component: AddEmpComponent }, { path: 'update-emp', component: EditEmpComponent } ];

JSON SERVER https://www.npmjs.com/package/json-server  npm install -g json-server  Create a src/db.json file with some data 

{ "employees": [ { "id": 2, "employee_name": "Ranjit", "employee_salary": 154000, "employee_age": "29" }, ]

} //json-server --watch db.json

FORM Add-emp.component.html

{{empformlabel}}



Form value: {{ addForm.value | json }}





//add-emp.component.ts import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup } from '@angular/forms'; import { EmployeeService } from '../service/employee.service'; import { Router } from '@angular/router'; @Component({ selector: 'app-add-emp', templateUrl: './add-emp.component.html', styleUrls: ['./add-emp.component.scss'] }) export class AddEmpComponent implements OnInit { empformlabel = 'Add Employee'; empformbtn = 'Save'; constructor(private formBuilder: FormBuilder, private router: Router, private empService: EmployeeService) {} addForm: FormGroup; btnvisibility = true;

ngOnInit() { this.addForm = this.formBuilder.group({ id:'', employee_name:'', employee_salary:'', employee_age:'' });

} onSubmit() { console.log('Successfully Created'); this.empService.createUser(this.addForm.value) .subscribe(data => { this.router.navigate(['list-emp']); }, error => { alert(error); }); } }

//List-emp.component.ts import { Component, OnInit } from '@angular/core'; import { EmployeeService } from '../service/employee.service'; import { Employee } from '../model/employee.model'; import { Router } from '@angular/router'; @Component({ selector: 'app-list-emp', templateUrl: './list-emp.component.html', styleUrls: ['./list-emp.component.scss'] }) export class ListEmpComponent implements OnInit { employees: Employee[]; constructor(private empService: EmployeeService, private router: Router ) {}

ngOnInit() { this.empService.getEmployees() .subscribe((data: Employee[]) => { this.employees = data; }); }

deleteEmp(employee: Employee): void { this.empService.deleteEmployees(employee.id) .subscribe(data => { this.employees = this.employees.filter(u => u !== employee); }); } editEmp(employee: Employee): void { localStorage.removeItem('editEmpId'); localStorage.setItem('editEmpId', employee.id.toString()); this.router.navigate(['update-emp']); } addEmp(): void { localStorage.removeItem('editEmpId'); this.router.navigate(['add-emp']); } }

User Details

Id Employee Name Salary Age
{{emp.employee_name}} {{emp.employee_salary}} {{emp.employee_age}}


Edit-emp.component.html

{{empformlabel}}



Form value: {{ editForm.value | json }}



Edit-emp.component.ts import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup} from '@angular/forms'; import { EmployeeService } from '../service/employee.service'; import { Router } from '@angular/router'; @Component({ selector: 'app-edit-emp', templateUrl: './edit-emp.component.html', styleUrls: ['./edit-emp.component.scss'] }) export class EditEmpComponent implements OnInit { empformlabel = 'Edit Employee'; empformbtn = 'Update'; constructor(private formBuilder: FormBuilder, private router: Router, private empService: EmployeeService) { } editForm: FormGroup;

ngOnInit() { this.editForm = this.formBuilder.group({ id: '', employee_name: '', employee_salary: '', employee_age: '' }); const empid = localStorage.getItem('editEmpId'); if (+empid > 0) { this.empService.getEmployeeById(+empid).subscribe(data => { this.editForm.patchValue(data); }); } } onUpdate() { console.log('Update fire'); this.empService.updateEmployee(this.editForm.value).subscribe(data => { this.router.navigate(['list-emp']); }, error => {alert(error);}); } }

FORMS 

1. 2. 

1. 2. 3. 4.

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({

selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent {

title = 'forms'; form =new FormGroup( { id:new FormControl(''), name:new FormControl('',Validators.required), mobile:new FormControl('',Validators.required), email:new FormControl('',[Validators.required, Validators.email]), pass:new FormControl('',[Validators.required, Validators.minLength(6)]), }); onSubmit(){alert(JSON.stringify(this.form.value));} }

CONT.. App.component.html

Reactive Forms

Name is required!!!


CONT..
Mobile number is required!!!
Email is required!!
Valid Email is required!!!


CONT..
Password is required!!!




THANK YOU

Related Documents

Angular 8
January 2021 0
Velocidad Angular
January 2021 3
Angular-9
January 2021 0
Angular Http Client Guide
January 2021 0
Livro Angular Js
March 2021 0
8
February 2021 3

More Documents from "Marcio De Souza Rocha"