0% found this document useful (0 votes)
39 views39 pages

Ebook de Angular

Uploaded by

Cesar Espinoza
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
39 views39 pages

Ebook de Angular

Uploaded by

Cesar Espinoza
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 39
~LEARNING Angular Free unaffiliated eBook created from Stack Overflow contributors. Table of Contents About. Chapter 1: Getting started with Angular. Remarks. Versions. Examples. Installation of Angular using angular-cli Prerequisites: To setup a new project. To add to an existing project Running The Project Locally Generating Components, Directives, Pipes and Services ‘Angular "Hello World” Program. Prerequisites: Step 1: Creating a new project. ‘Step 2: Serving the application ‘Step 3: Editing our first Angular component. Chapter 2: Event Emitter Examples. Catching the event Chapter 3: For Loop. Examples. NaFor - Markup For Loop. Chapter 4: Forms. Examples. Reactive Forms. app.module.ts. ‘app.component.ts. app.component.ntm! validators.ts ao N 2 ® ® ® d cy 10 10 13 13 13 15 15 15 16 16 16 16 16 17 18 ‘Template Driven Forms. ‘Template - signup.component.html ‘Component - signup.component.ts Model - signup-request.model.ts. ‘App Module - app.modble.ts ‘App Component - app.component.html Chapter 5: Pipes. Introduction Examples. Custom Pipes Muttiple custom pipes. Chapter 6: Routing Examples. Routing with chidren Basic Routing Chapter 7: RXJS and Observables. Examples. ‘Watt for multiple requests. Basic Request. Chapter 8: Sharing data among components. Introduction Remarks. Examples. Sending data from parent component to child via shared service ‘Send data from parent component to child component via data binding using @Input. Sending data from child to parent via Output event emitter. ‘Sending data asynchronous from parent to child using Observable and Subject. Credits. 18 18 19 19 20 20 21 21 21 2 22 24 24 25 28 28 28 28 29 29 29 29 30 31 32 About You can share this PDF with anyone you feel could benefit from it, downloaded the latest version from: angular It is an unofficial and free Angular ebook created for educational purposes. All the content is extracted from Siack Overflow Documentation, which is written by many hardworking individuals at Stack Overflow. It is neither affiliated with Stack Overflow nor official Angular. The content is released under Creative Commons BY-SA, and the list of contributors to each chapter are provided in the credits section at the end of this book. Images may be copyright of their respective owners unless otherwise specified, All trademarks and registered trademarks are the property of their respective company owners. Use the content presented in this book at your own risk; it is not guaranteed to be correct nor accurate, please send your feedback and corrections to [email protected] https:/riptutorial.com/ 1 Chapter 1: Getting started with Angular Remarks Angular (commonly referred to as "Angular 2+" or "Angular 2") is a TypeScript-based open- source front-end web framework led by the Angular Team at Google and by a community of individuals and corporations to address all of the parts of the developer's workflow while building complex web applications. Angular is a complete rewrite from the same team that built Anguiar/S. The framework consists of several libraries, some of them core (@angular/core for example) and some optional (@anguilar/animations). You write Angular applications by composing HTiV\l. templates with Angularized markup, writing component classes to manage those templates, adding application logic in services, and boxing components and services in modules. Then you launch the app by bootstrapping the root module. Angular takes over, presenting your application content in a browser and responding to user interactions according to the instructions you've provided. Arguably, the most fundamental part of developing Angular applications are the components. A component is the combination of an HTML template and a component class that controls a portion of the screen. Here is an example of a component that displays a simple string: src/epp/app.component.ts import { Component } from ‘@angular/core'; ect -app', template: °Hello ( {name} } AppComponent, tangular'; Every component begins with a ecomponest decorator function that takes a metadata object. The metadata object describes how the HTML template and component class work together. The setector property tells Angular to display the component inside a custom tag in the index.htm’ file. index.html (inside the bozy tag) Loading AppComponent content here ... The template property defines a message inside a header. The message starts with "Hello" https:/iriptutorial. com/ 2 and ends with | jsane)), which is an Angular interpolation binding expression. At runtime, Angular replaces ((nane)) with the value of the component's nae property. Interpolation binding is one of many Angular features you'll discover in this documentation. In the example, change the component class's name property ffom :arcuiar' tO ‘woria* and see what happens This example is written in TypeScript, a superset of JavaScript. Angular uses TypeScript because its types make it easy to support developer productivity with tooling. Additionally, almost all support is for TypeScript and so using plain JavaScript to write your application will be difficult Writing Angular code in JavaScript is possible, however; (his guide explains how. More information on the architecture of Angular can be found here Versions —_ 5.0.0-beta.1 (Latest) 2017-07-27 43.2 2017-07-26 5.0.0-beta.0 2017-07-19 43.1 2017-07-19 43.0 2017-07-14 4.2.6 2017-07-08 42.5 2017-06-09 4.2.4 2017-06-21 42.3 2017-06-16 42.2 2017-06-12 4.2.1 2017-06-09 4.2.0 2017-06-08 4.2.0-4c.2 2017-06-01 4.2.0.1 2017-05-26 4.2.0.0 2017-05-19 41.3 2017-05-17 44.2 2017-05-10 https:/riptutorial.com/ 3 ATTY Leese 444 2017-05-04 41.0 2017-04-26 4.1.0-10.0 2017-04-21 403 2017-04-21 40.2 2017-04-11 40.1 2017-03-29 4.0.0 2017-03-23 4.0.0-10.6 2017-03-23 4.0.0-0.5 2017-03-17 4.0.0-r0.4 2017-03-17 2.4.10 2017-03-17 4.0.0-10.3 2017-03-10 249 2017-03-02 4.0.0-r0.2 2017-03-02 4.0.0-re.4 2017-02-24 248 2017-02-18 247 2017-02-09 246 2017-02-03 245 2017-01-25 24.4 2017-01-19 243 2017-01-11 24.2 2017-01-06 244 2016-12-21 24.0 2016-12-20 23.4 2016-12-15 https:/riptutorial.com/ ATTY Leese 2.3.0 2016-12-07 2.3.0-r6.0 2016-11-30 2.24 2016-11-30 223 2016-11-23 2.2.2 2016-11-22 22.4 2016-11-17 2.2.0 2016-11-14 2.2.0-10.0 2016-11-02 2.1.2 2016-10-27 2.1.1 2016-10-20 2.1.0 2016-10-12 2.1.0-1¢.0 2016-10-05 2.0.2 2016-10-05 2.0.1 2016-09-23 2.0.0 2016-09-14 2.0.0-0.7 2016-09-13 2.0.0-1¢.6 2016-08-31 2.0.0-0.5 2016-08-09 2.0.0-r0.4 2016-06-30 2.0.0-re.3 2016-06-21 2.0.0-r0.2 2016-06-15 2.0.0-r¢.1 2016-05-03 2.0.0-r0.0 2016-05-02 Examples https:/riptutorial.com/ Installation of Angular using angular-cli This example is a quick setup of Angular and how to generate a quick example project. Prerequisites: + Node js 6.9.0 or greater. + ppm v8 or greater or yarn. + Typings v1 or greater. Open a terminal and run the commands one by one: pm install -g typings Of yarn global add typings apm install -g @angular/eli Of yarn global add tangular/eli The first command installs the ‘yp ngs library globally (and adds the cypings executable to PATH). The second installs @angular/cli globally, adding the executable na to PATH. To setup a new project Navigate with the terminal to a folder where you want to set up the new project. Run the commands: ng new PROJECT_NAME Ag serve That is it, you now have a simple example project made with Angular. You can now navigate to the link displayed in terminal and see what it is running. To add to an existing project Navigate to the root of your current project. Run the command: This will add the necessary scaffolding to your project. The files will be created in the current directory so be sure to run this in an empty directory. Running The Project Locally https:/iriptutorial. com/ 6 In order to see and interact with your application while it's running in the browser you must start a local development server hosting the files for your project. ng serve If the server started successfully it should display an address at which the server is running. Usually is this: at Out of the box this local development server is hooked up with Hot Module Reloading, so any changes to the html, typescript, or css, will trigger the browser to be automatically reloaded (but can be disabled if desired), Generating Components, Directives, Pipes and Services The ng generate (OF SiMply rg g ) command allows you to automatically generate Angular components: # The command below will generate a component in the folder you are currently at ng generate component ny-generated-component # Using the alias # You can add Ag g component m P lat create new folder # You can add --spec false if you don't want a test file to he generated (my-generated- component. spec. ts) There are several possible types of scaffolds angular-cli can generate: eR MMU) Module ng g sodule my-new-module Component — ag g component _ny-new-conponent, Directive ng g directive my-new-directive Pipe 1¢ g pipe my-new-pipe Service ng g service my-nev-service Class gg class ny Interface ng g interface my-new-interface https:/iriptutorial. com/ a MRE) Enum ng g enum my-ne: You can also replace the type name by its first letter. For example: 19 4 my-newmodure to generate a new Module OF ny ¢ © my-new-component to Greate a component. Building/Bundling When you are all finished building your Angular web app and you would like to install it on a web server like Apache Tomcat, all you need to do is run the build command either with or without the production flag set. Production will minifiy the code and optimize for a production setting ng build or ng build —-prod Then look in the projects root directory for a /a:s: folder, which contains the build. If you'd like the benefits of a smaller production bundle, you can also use Ahead-of-Time template compilation, which removes the template compiler from the final build: ag build --p: aot Unit Testing Angular provides in-built unit testing, and every item created by angular-cli generates a basic unit test, that can be expended. The unit tests are written using jasmine, and executed through Karma. In order to start testing execute the following command: ng test This command will execute all the tests in the project, and will re-execute them every time a source file changes, whether it is a test or code from the application For more info also visit: anguler-cl github page Angular “Hello World" Program Prerequisites: Setting up the Development Environment Before we get started, we have to setup our environment. https:/riptutorial.com/ + Install Node js and npn if they are not already on your machine. Verify that you are running at least node 6.9.x and nom 3.x.x by running node -v and npm_-v in a terminal/console window. Older versions produce errors, but newer versions are fine. + Install the Angular CL! globally using nm nsta11 -g @angular/eli. Step 1: Creating a new project Open a terminal window (or Node.js command prompt in windows). We create a new project and skeleton application using the command: ng new my-ape Here the ss is for Angular. We geta file structure something like this. 4 MY-APP » eve » node modules > app > assets > environments 4 faviconsico © indexhtml TS mainte 18 polyfillsts # styles.css TS testis {} tsconfigappjson {} tsconfigspecjson TS typings.d.ts {} angular-clijson © .editorconfig Q sitignore X karmacontjs 4) packagejson 38 protractorcontjs @ READMEmd {1} tsconfig son {} tslintjson https:/iriptutorial. com/ There are lots of files. We need not worry about all of them now. Step 2: Serving the application We launch our application using following command: We may use a flag -opea( or simply -c) which will automatically open our browser on ne tps //Localhost :4200/ Ag serve --open Navigate browser to the address rtp: //1oce1) 4200/. It lOOks Something like this: @ MyApp x © © locathost4 Welcome to : A Step 3: Editing our first Angular component https:/iriptutorial. com/ 10 The CLI created the default Angular component for us. This is the root component and itis named app-zoot. One ean find it in . /s:c/app/app.component .s. Open the component file and change the title property from weicome to app!! tO Hello World. The browser reloads automatically with the revised title. Original Code : Notice the ticie = *app'; import { Component } from *@angular/core’; Angular CLI, 20 minutes ago | 1 author (Angular ¢ @Component({ selector: ‘app-root’, templateUrl: *./app.component.html’, styleurls: [‘./app.component.css*] » export class AppComponent { title = ‘app’; } Modified Code : Value of + ic1e is changed. inport { Component } from *@angular/core’ ; @component ({ selector: ‘app-root’, templateUrl: *./app.component html", styleUrls: ['./app.conponent.css"] » export class AppComponent { title = ‘Hello World’; } Similarly there is a change in ./src/app/app. Original HTML,
{{title}}!! nav 1 |click ne)
» export class Navigation { constructor (private navService:tavService) {} https:/iriptutorial. com/ 13 selectedNaviten (item: number) { console.log("selected nav item ' + item); this. navService.enitNavChangeEvent (item) ; Read Event Emitter online: https://riptutorial com/angular/topic/9828/event-emitter https://riptutorial.com/ 14 Chapter 3: For Loop Examples NgFor - Markup For Loop The NgFor directive instantiates a template once per item from an iterable. The context for each instantiated template inherits from the outer context with the given loop variable set to the current item from the iterable. To customize the default tracking algorithm, NgFor supports trackBy option. trackBy takes a function which has two arguments: index and item. If trackBy is given, Angular tracks changes by the return value of the function.
  • {(1h) = ({item.name}) Additional Options: NgFor provides several exported values that can be aliased to local variables: + index will be set to the current loop iteration for each template context. first will be set to a boolean value indicating whether the item is the first one in the iteration. last will be set to a boolean value indicating whether the item is the last one in the iteration. even will be set to a boolean value indicating whether this item has an even index. ‘odd will be set to a boolean value indicating whether this item has an odd index. Read For Loop online: https://riptutorial.com/angular/topic/9826/for-loop https:/iriptutorial. com/ 15 Chapter 4: Forms Examples Reactive Forms app.module.ts Add these into your app.module.ts file to use reactive forms import { NgModule } rrom ‘eanguiar/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule, ReactiveFormsModule } from '@angular/forns'; import { AppComponent } rrom *./app.component'; @igModule ( imports: | Erowserliodule, FormsModule, ReactiveFormsModule, 7 declarations: [ AppConponent ] providers: (J, bootstrap: [ AppConponent ] » export class AppModule (} app.component.ts import { Component, OnInit } from '@angular/core'; import template from './app.component -html'; import ( FornGroup,FornBuilder, Validators } from '@angular/forns'; import { matchingPesswords } fron './validators'; @component ({ selector: ‘app', template » export class AppComponent implements Onini: ( addForm: FormGroup: constructor (private formBuilder: FormBuilder) ( ) ngOninit() | this.addForm = this. formauilder.group|( beernane: ['', Validators. required), email: ['', Validators. required], role: ["", Validators.requiredl, password: [1", Validators. required), password2: ['', Validators.required] } ( validato: matchingPasswords (*password', ‘password2") }); https:/iriptutorial. com/ 16 ui addUser () { if (this.addForm.valid) { var adduser = ( usernane: this.addForm.controls|‘usecnane'].value, email: this.addForm.controls['email'] value, password: this addForm.controls|'password') value, profile: | role: this.addForm.controls['role'] .value, name? thie.addForm.controis['usernane"}.value, email: this-addForm.controls["email'] .value Ms console. log (adduser);// adduser var contains all our form values. ven enat this.addForm.reset ();// this will reset our form values to null app.component.html
    Passwords do not match
    br /> e/aivs \ddUser () "> validators.ts export function matchingPassnords (passwordKey: string, confirmPasswordKey: string) ( return (group: ControiGroup): ( Ikey: string]: any det let password = group.controis[rasswordKey] + let confirmPaseword = group.cont rols[confirmPasswordkey]; 42 (paseword.value return ( mismatchedPasswords: true confirmPaseword.value) ( » Template Driven Forms Template - signup.component nem
    Sign Up,
    usernane
    https:/iriptutorial. com/ [(ngModeL)
    'signUpRequest.email® />
  • » export class AppComponent ‘7 6. Link the other routes. By default, scuteroutet will load the component for which empty path is specified in the soutes. rovtersink directive is used with html anchor tag to load the components attached to routes. soute:tinc generates the href attribute which is used to generate links. For example: Amport { Component ) from ‘@angular/core'; @component ({ selector: ‘demo-app', template: Login signup Dashboard
    https:/iriptutorial. com/ 26
    » export class AnotherComponent { } Now, we are good with routing to static paths. souteriink supports dynamic path too by passing extra parameters along with the path. import ( Component } from *@angular/core'; @Component ({ selector: ‘deno-app', template:
    • (jbar.nane} let bar of bars | agynet>
    » export class SecondComponent { } sousertink takes an array where the first parameter is the path for routing and subsequent elements are for the dynamic routing parameters. Read Routing online: https://riptutorial.com/angular/topic/9827/routing https:/iriptutorial. com/ 27 Chapter 7: RXJS and Observables Examples Wait for multiple requests One common scenario is to wait for a number of requests to finish before continuing. This can be accomplished using the... method. In the following example, sorkcoin is used to call two methods that retum onsexvabies. The callback specified in the .subscrsbe method will be called when both Observables complete. The parameters supplied by . suscrine match the order given in the call to . sorkuoin. In this case, first posts then tags. loadData() + void { Observable. forkJoin( this.blogApi.getPosts(), this.blogapi..getTags () ).subscribe((([posts, tags]: (Post {], Tagl]]) => ( this.posts = posts; this.tags = tags; me Basic Request The following example demonstrates a simple HTTP GET request. ncep.ce: () retums an obseevabie Which has the method sunscsive. This one appends the returned data to the poses array. var posts = [1 gerPosts (http: Http): ( this-http.get (“https://jsonplaceholder. typicade.com/posts*| -subscribe (response => { posts.push(response. json()); ne Read RXJS and Observables online: https://riptutorial.com/angular/topic/9829/rxjs-and- observables https:/iriptutorial. com/ 28 Chapter 8: Sharing data among components Introduction The objective of this topic is to create simple examples of several ways data can be shared between components via data binding and shared service. Remarks There are always many of ways of accomplishing one task in programming. Please feel free to edit current examples or add some of your own. Examples Sending data from parent component to child via shared service service.ts: import { Injectable } fron '@angular/core'; @Injec eo 38 AppState ( export c! oF public mylis parent.componentts: import {Component} fron 'Cancular/core'; import { AppState } from './shared.service'; @component (( selector: ‘parent-example', cemplateUrl: ‘parent.conponent.ntnl', » export class ParentComponent { mylistFromarent = {17 constructor (private appState: Appstate) { this.appstate.mylist; ) aay) { this-appState.mylist .push({"itenNare":"Sonethina"}) ; } parent.component.html: https:/iriptutorial. com/ 29

    Parent

    cbutton (click
    lad Q ">Adde /iat ton> child.component.ts: import (Component, Input } from '@angular/core'; import ( Appstate } from ‘./shared.service'; @component (( selectcr: ‘child-component', template:

    Child powered by shared service

    {imyiist | Json}) » export class ChildComponent { mylist: any: constructor (private appState: AppState) { this.mylist = this.appState.mylist: } Send data from parent component to child component via data binding using @Input parent.component.ts: import (Component} fron ‘@angular/core'; @component (( selector: ‘parent-example", cemplateUri: ‘parent.component-ntni", » export class PazentComponent ( nylistFromarent = (|; addi { this.mylistFromParent .push ({"itemName": "Something" }); } parent.component.html:

    Parent

    You might also like