cittadelmonte.info Fiction Practical Angular 2 Pdf

PRACTICAL ANGULAR 2 PDF

Wednesday, March 20, 2019


Web Essentials: Mastering Angular 2 covers Angular 2 and provides practical and hands-on If you are building for the web, learning Angular 2 will change the. Angular 2. From Theory To Practice. Asim Hussain. Version , One practical application of @ViewChild is to get access to template local. Angular 2. A Practical Introduction to the new Web Development Platform Angular 2 (cittadelmonte.info, cittadelmonte.info 2, AngularJS, AngularJS 2, ng2). Sebastian.


Practical Angular 2 Pdf

Author:KARAN STEPNOWSKI
Language:English, Spanish, Portuguese
Country:Malta
Genre:Health & Fitness
Pages:728
Published (Last):11.01.2016
ISBN:724-7-38523-974-1
ePub File Size:23.70 MB
PDF File Size:16.25 MB
Distribution:Free* [*Regsitration Required]
Downloads:38732
Uploaded by: KALLIE

This books shows all the steps necessary for the development of SPA (Single Page Application) applications with the brand new Angular 2 (still in beta). Practical Angular 2: With Node/npm, Typescript, SystemJS and Visual Studio Code: Create web applications with the new Angular 2 framework. Learn Angular 2 step by step. By cittadelmonte.info Version (Beta). This book is in very preliminary stage, but if you are beginner in angular it will still.

Skip to main content. Log In Sign Up. Practical Angular 2 - Daniel Pedrinha Georgii. Mahadya Suta. Leanpub empowers authors and publishers with the Lean Publishing process. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools and many iterations to get reader feedback, pivot until you have the right book and build traction once you do.

The event is dispatched on the onButtonOkClick method. In the AppComponent we add the event to the template: For example, to fill the data on the video list, we used a simple array populated in the AppComponent. In real applications the data should be requested from a server with a service for this task. We will talk about it on a further chapter. There are also many other features in Angular 2 that helps when working with forms, that we will also see in a further chapter.

In other words, when we create a component, we can use it anywhere on our application. One of the main features of componentization is the creation of components inside components. For the next example, copy the AngularBase and paste it as AngularPanel and add the bootstrap with the command: Now we can create the title property like this: We can use it on the template like following: By compiling the application we have the following interface: Now change the AppComponent template: It is also possible to add components inside components, which allows the creation of screens reusing HTML code: Some theory In this chapter we will see some theory about Angular 2.

We had a first impression with the previous chapters so now we should learn deeper the most important concepts of the framework. From that image we can highlight some key points to master the framework. They are: A module name is the same as its file name. In the previous chapter example AngularPlayList we have examples of modules with the same name of the class, like: That way it is possible to import it in anywhere in the application.

For instance: A library may contain components, directives, services, etc. Suppose an Angular application in which the model classes that represents an object are grouped on the model directory as on the following examples: You can create the model.

All the properties are defined by its api, available here. A component in Angular 2 has the concept of relative design, in other words, the visual changes on the component are not defined accessing the DOM directly, but changing the component states.

In the previous chapter, when the user clicked on the video list, a new component appeared on the screen showing the video details. Every time we create an application it is necessary to think in how to split it into components in a way that they can exchange information.

A template has HTML code, directives, event calls and other templates. A full example of a template was on the previous chapter: It will use the value of the title variable from the class in the template. It is possible to use this databind in tags and html attributes, as on the following example: See the following example: The use of the asterisk indicates to Angular that this property may change the page DOM. This will change the way Angular treats this component so it can be optimized.

There is also the TwoWay DataBind, that is indicated with [ target ] as on the following example: Notice the use of the asterisk again indicating that this directive changes the application DOM. The directive can be added to the element that will be repeated. On the previous chapter example we used: If you want to use the array index, change the expression to: The following example illustrates this behavior: Angular uses decorators as on the following example: It is also possible to use the template as a metadata: In fact the service class is an ordinary TypeScript class, but with the concept of data manipulation.

On the chapter about Ajax we will see more details on how these classes works. Angular uses this concept to make easier the instantiation of classes by the components, providing the class instance automatically.

Which means that if we change the property of an injected class, this change will still be active if the class is injected somewhere else.

Or define the class on the Component decorator: After the setup it is possible to use the following syntax to inject an instance of the class: On the following example, the TestService class generates an execution error, because there is no metadata related to it, and it uses dependency injection with the Http class: Forms are used for the entry of data and is necessar y to control how this entry is done and if the data provided by the user is valid.

Angular 2 provides the following features: Make the model. To do it we must use the following syntax: A simple way to check the user variable of the AppComponent class is to use the following template above the form: The result should be similar to the following: Notice that by changing the value of the text box, the value of the user object is changed automatically.

It is also possible to track the state of each component, allowing to know when a component was changed, invalidated, etc. Besides checking the actual state of the control it is possible to add css styles to it, highlighting the control states, for example, an error state.

To enable this validation it is necessary to use the ngControl directive passing the property to be tracked: For instance, the name field has the required instruction, that defines the field as mandatory. If this field is filled, the ng-invalid css class will be added to it. We can then use some css to show an information to the user.

cittadelmonte.info | Angular Js | Json

First create the styles. Delete the text from the Name field and Email and notice that the style was applied, with a red border as the following image: Fill again the fields and notice that the style is removed. To create this variable, use the followed by the name of the variable and its value.

In the case of the name field we have: For that it is necessary to create a variable that represents the ngForm. With this variable it is possible to use [hidden] to define what will be visible: The web server can be made in any language java, php,.

Net, etc , but the communication between a server and the client application must follow a pattern. This pattern, in this case, is the json, a data text format that can represent objects or array of objects.

The first test we will do is accessing an URL to get json data. For that, create the following file on the project: You should get the following response: Add the http. As we learned previously, the providers property can be replaced on the bootstrap of the application, in the file boot.

Inject the Http class into the component: It is even possible to use a class variable, as on the following example: With the class already injected, we will use it to access the server via Ajax.

As we used the live-server, using the path. To access this address via GET we use: The first is the map method that will format the return text from the server, and the second is the subscribe that will attribute the formatted text to a variable.

This is possible because the server returns a text in json format. The subscribe method attributed the response already formatted in json to the variable this.

It is possible instead of attributing the value to a variable, call a method on the class, for example: With the this. On the following example, we have the AppComponent class ready: The result of this component is as follows: A service class is responsible to provide data to the application, so it is natural to create the UserService class for that purpose.

Create all the application classes inside the app directory. Create the services directory with the user. And create the services library inside the app directory. Create the user directory with the user. The worst option is the first, that should be used only when learning or testing a small project. An Angular 2 project divides itself into many files and store them in only one directory is not a good practice. For example: Notice that this organizes the files that represent entities of the application are mixed.

In other words, to work with products you will need to open many files in many directories. It becomes not effective when there are too many files in the same directory. This option is better than the first, but works only for small projects. The third option separates the entities of the application in distinct directories like the following: This option separates each entity in a directory, adding related files to that entity.

This way when the project becomes big there will e many directories, but each one represents an unique peace of the application. We will call it User model. In bigger projects it is possible to encapsulate those variables.

By creating the User model, we can add it to the model library like the following: The use of.. We used Injectable to set up the dependency injection into the class. I makes possible to inject the Http class into the UserService class. When we created the constructor, we inject the instance of the Http class into the http variable, that can be used in other method of the class.

To be able to inject the Http class, we must use the providers metadata or change the bootstrap of the application. This method uses the Http class to make the GET request to the.

And on the server response, the map method is called, where the. Notice that we are returning the this. The code that calls getUsers that is responsible to manage the return. This is realized on the AppComponent. To create a services library, create the following file: This means that we can use the dependency injection inside the constructor. The constructor will call the method userService. Instead of the http. Routes The definition of routes in Angular 2 follows the concept of splitting the code in smaller parts that can be loaded via Ajax by the framework itself.

First, add the router. When the application is still under development we use the. When the application is already in production we use the.

Each part has its own component and template, that are set up via the Router. First create the following components: Many settings should be done in the app.

HomeComponent, useAsDefault: In RouteConfig we define routes, where each one has at least three parameters: The URL path. The name of the route. The component to be loaded. There is also the useAsDefault: To test the routes, we will create a small menu that points to the three already created components. At first, this menu will be on the AppComponent template: Final example - Server After reviewing all the relevant concepts of Angular 2, we will create a working example of how to integrate Angular 2 to a server API.

The goal of this application is to create a simple blog with Posts and Users and a login interface. It is the web server responsible responsible for the API. We will not use the live-server but the express has the auto-loading feature with the nodemon library. It is an adapter for the MongoDB data base that is a NoSql data base with features almost as good as a relational data base.

It is a node library used for authentication via web token. We will use it for the user login.

All those technologies can be installed with npm as follows. It can be installed in your computer and used, but we will use the https: Access the link https: After logging in on the administration screen, create a new instance as the following image: On the next screen choose the Single-node tab and the Sandbox free plan: Choose a name, line blog and click on Create new MongoDB deployment.

On the next screen, access the data base and check if you get the following message: After creating the user we will use the connection URI as indicated on your administration screen: The app directory will contain the Angular 2 TypeScript code, that will be compiled to the public directory. This means that the files with the. String, login: String, password: With the Schema we created a model similar to a data base table in other data bases called User, that has the name, login and password fields.

And here is the Post model: String, author: String, body: String, user: ObjectId, ref: Date, default: In a production server you must change this key to any other text. Remember to change the connection address with the one you created before.

Router ; The 16th line creates the router which prepares the express to behave as an API. A router is responsible to get requests and execute a code depending of the format of the request. Usually we have four types of requests: Used to get data.

Can be used via the browser with an URL. Used to insert data, usually from a form. Used to delete data. Can be used to edit data. We will not use PUT in this project, but you can use it if desired. Besides the type of request we also have the url and the parameters that we will see further up.

This concept is similar to the webroot directory from other web servers. The console. This information should be used only in development environment. The text produced by this line should be similar to the following: The method JSON.

At line 27 the next method was used so the request continues its processing. When the user logs in it gets a token that will be used in every request. At line 31 the token variable gets the content of the token from the client.

In this case we will use the http header with the x-access-token variable. At lnie 34 the jwt. Notice that the secredKey is used there and that the third parameter is a callback function. At line 35 we check if the callback function got an error, which means that the token is not valid and returns the status code res.

At line 40 if no error is found the decoded object is stored in the req. At line 46 if no token was sent by the client the status code is sent back.

With the router. This callback sets up the router response with the res. If valid is valid the callback is executed and an array with the users is sent back to the client. Notice that here it is not necessary to be authenticated with a token. At lina 65 We used the properties of the User Schema to save the registry with the client data from req. The user. At line 77 with the property isNew we check if the user is trying to log in or sign in. If req. If incorrect the status code is returned. The sort method sorts the posts in the array and the populate method adds a reference to the user model for the post author.

PORT ; app. We also defined in which ports the server express will be listening. If the server. One of this programs is Postman, that can be installed as a plugin for Google Chrome. For example, to test the address http: Notice that we got the hello world response as set on the server. Since it will go through the auth middleware, the following error will be returned: To log in we access the URL on the following way: Notice that by sending login and password the token is generated and returned to the postman.

Copy and paste this token some where so we can use it on the next requests. In Angular, this token will be stored in a variable. Notice that with the token, the user data is returned. If you change the token, you will get the Failed to authenticate error.

Practical Angular 2

Try it. Final Example - Client application With the server ready, we can start our Angular 2 structure. On the express server, we set the static JavaScript files like the following: As the index.

For this, it is necessary to set up the tsconfig. In this context we use the. The AppComponent class can be, at first, like this: This is our directory structure: To test it on the browser, go to the command line on the blog directory and execute: And for that we will create a template called appComponent.

This is necessary because only the public directory is visible to the application. In this template we can use some css classes from bootstrap to style the application. At first, we can use the following HTML code: Split the application in components. Set up the AppComponent. Include the menu.

In this blog we will have three views: Shows all the posts 2. Login form 3. With this library we can reference the component classes like the following: Then we use the RouteConfig to create three routes linking them to the created components. Instead of programming this component call, we will create a service called PostService and the Post model with the definition of a Post: And also create the library: The getPosts method will make an Ajax request to the.

Since we will show the posts on the main page, we must set up the HomeController to access this service: That way we can inject it into the constructor method. After injecting it we call postService. Notice that the posts will be stores in the variable this. And finally we edit the component template to: The result should be similar to the following image: UserService, private loginService: LoginService, private router: We will create those files soon.

We also have here two variables to control the application template. The full template of the LoginComponent: Every Http request from the client to the server has a header in which we can send some information.

In this case, we are sending Content-Type and x-access-token. In the LoginComponent we have the Login button with the following action: When the button is clicked the method onClick from the LoginComponent class is called: It is also important to hide the form, to avoid the user from clicking again on the button.

The insert method from the userService class is called to connect to the server sending this. When the service returns the data from the server, the subscribe method is executed. It has two callbacks: Each one has its own method to process the data. The onLoginResult method is executed when tue user is authenticated.

We use the LoginService class to inform this login and it will and it will be accessible anywhere in the application one of the advantages of using dependency injection. And then we use the router to go back to Home. Notice that the div will become visible by just setting the this. But here we used the LoginService to check if the user is logged in, and if not, redirect him to the login form. You can choose however is best for your project. This view template is the following: Within the scripts section we are defining command shortcuts which can be executed via the npm command.

No more steps needed. The compiler runs before the application files are sent to the browser and transforms TypeScript to valid JavaScript code. We will get back to that section and see how we can make use of these commands at the end of this chapter. The command uses the typings. In the example from above you can see that four development dependencies are listed: The first section is named compilerOptions and contains command line options which are passed to the TypeScript compiler every time the program is executed.

Using types in your JS code is very easy. So create that file and insert the following JSON code: The tsconfig. If you prefer another loader you can skip SystemJS and install the loader you like most e.

Before attaching the TypeScript configuration to our project. Herewith it is ensured that the resulting JavaScript code can be interpreted by modern browsers even if they are not supporting ECMAScript yet. As we would like to make use of TypeScript in our project we need to store a TypeScript compiler configuration file in our project. Writing your First Angular 2 Application 7 TypeScript Compiler Configuration After having installed all of the project dependencies via npm there is one more step to complete before actually starting to write code.

If you want to have additional information about the meaning of the various TypeScript compiler options please take a look at https: This TypeScript configuration file is named tsconfig. Please note. Therefore the file systemjs. SystemJS needs to be configured.

SystemJS configuration in file systemjs. The first think you should notice is the a map object is created and filled with properties. As a parameter this object is passed to the call of System. The next thing the configuration code is doing is to register all packages which may be used in the project. The configuration code is a bit complicated to read. Herewith we tell SystemJS where to look when we import modules. Writing your First Angular 2 Application 9 38 defaultExtension: Create the index.

The packages are stored in the packages object. Implementation First of all. Basic structure of file index. These are the libraries which we installed via NPM in the last section and now include in our web application to make use of them. Furthermore the app module is imported and run. As every module the application module is implemented by using a class and attaching the NgModule decorator as you can see in the code listing.

Furthermore a module definition can also contain the following properties: This property can be used when declaring function modules.

Every application module needs to import BrowserModule. The exports property contains a list of components. The imports array is used to list all dependencies other modules which needs to be made available to the module.

A list of dependency injection providers e. Function modules can be imported by the application module or other function modules and comprise components. Within the decorator block you can find the following properties which are used for configuration: The array which is assigned to the declarations property contains all compo- nents.

Each Angular 2 application has at least one module: By importing this standard module we get access to browser specific renderers and Angular 2 standard directives like ngIf and ngFor.

This application module has the conventional name of AppModule and is implemented in the file app. The example from above defines that AppComponent should be loaded first. Of course this is no surprise as this is the only component of our sample app.

The class only contains an empty constructor and the decorator is added Component. We will change that now to: The value which is assigned to the template property is an empty string.

The value which is assigned is just an empty string so far. With this setting in place we are able to use the component in our HTML document like so: Components are organized in a hierarchical way. Every Angular 2 application is built by implementing components. Main Angular component in file app. Further components are used by the main components or by child components of the main components. With the decorator available.

Inside the Component-Annotation we use the selector property to define the name of the HTML-Element which should be used to include this component.

In the next step we will replace the empty string with the HTML template code which is needed to generate the output of the component. If you are familiar with Angular 1. To access the property value the expression is included in the template by using double curly braces: This makes Angular 2 standard directives available in all templates of components. To get the total number of items we can use the length property of the todos array. The first information which is printed out by the template is the total number of todo items available.

Please be aware: We are using the new EcmaScript template string feature to assign a multiline string containing the template code. All todo items will be stored in an array of strings named todos. Writing your First Angular 2 Application 13 Template code of main component 1 template: For each iteration the current todo item is available through the variable todo. For every element found in todos array the output of the element and its content is repeated.

This is the syntax which is used in Angular 2 to create a variable todotext which is accessible in the component class and gives us access to the HTML element. So the view implementation for our component is ready now. The class constructor is used to initialize the todos array with three items. Another thing to notice here is that the class keyword is preceded by export. The addTodo method is implemented in class AppComponent. This notation is used in Angular 2 to describe events.

angular2.pdf

By using the method System. The value which is assigend to the click event is a string containing an event handler method named addTodo. After the list of todos the template contains an input element and a button so that the user is able to add new todo elements. First we need to have an todos array in place containing all our todo items: Writing your First Angular 2 Application 14 listed in the declarations property of the NgModule decorator.

If you try to assign anything other as a string to the array the TypeScript compiler will run into an error because the type check fails. Loading Components and Bootstrapping the Application Now we have nearly all pieces together to get our Angular 2 application up and running except one. This method is not yet available and will be implemented in the next step. The method takes this string and calls the push method to extend the todos array with this new item. The addTodo method gets one parameter: The last thing we have to do is to adapt the MyApp component class a little bit to meet the expectations the template code has set.

Herewith we make the AppComponent available as a module. Create the file and insert the following lines of code: Here we are using the previously assigned variable todotext and access the user input value by using the property value. As you can see the file main. Running the Application Running the application basically consists of two steps: The code of the component is compiled to JavaScript which can be interpreted by the Browser directly and the corresponding template is used to generate the HTML output which is displayed to the user.

Writing your First Angular 2 Application 15 Importing modules and bootstrapping application in file main. To determine what needs to be displayed to the user. By executing platformBrowserDynamic. Most of the NPM scripts are executed by using the npm command in the following way: Here you can see that the scripts section of package. This scripts installs the TypeScript definition files defined in typings..

MISSY from Maine
I do enjoy reading books bleakly. See my other posts. I absolutely love camogie.