Showing posts with label Angular2. Show all posts
Showing posts with label Angular2. Show all posts

Monday, March 27, 2017

Getting Started with Angular2

Getting Started

Now let us start building our 'Hello World' application. To start, we will first create our HTML file, say index.html in the project folder and here we will add references to scripts and css that are required for our application and write our custom Angular Directives.
Yes, you read it right ‘custom Angular Directives’. “What this Directive mean”, may be the question in the mind of programmers new to this technology.
So, Let us understand what this ‘Directive’ mean here. To put it in simple way, we know many HTML elements or say tags like <p>, <h1> etc., All these tags have some predefined functionalities. Say, if browser comes across the tag <h1>, it understands as heading element with specific font-size and displays on browser accordingly. Similarly, what if we want to create our own custom elements with some definition and reuse that custom element in our application.
This custom element is called Directive. Both Angular JS 1.x and Angular2 have different ways of creating Directive and in this article we will be focusing on Angular2. We will be using Angular Directive in our index.html file
Now back to our index.html file.  Let us add some polyfills required for older browsers. I have also added :

<html>
<head>
<title>Angular 2 Sample</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 1. Load libraries -->
<!-- Polyfill(s) for older browsers -->
<script src="node_modules/core-js/client/shim.min.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/reflect-metadata/Reflect.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
</head>
<!-- 3. Display the application -->

<body>
<my-app>Loading...</my-app>
</body>
</html>
 

Notice, that I have added our custom angular directive <my-app> under <body> tag. The definition for this tag or say Directive will be written in Component and placed in typescript file (i.e, file with .ts as extension).
Currently, the content of this tag is “Loading…” which will be displayed on the browser until the actual definition is loaded.
So, Let us create our first Component in the steps below.

Step 1: - Creating a proper folder structure

Create a folder with name ‘app’ in the project folder ‘Angular2-Sample. In this folder, we will be placing our typescript files which contains logic.
Let us understand the significance of name of the ‘app’ folder before directly jumping into code.
For that, If we go through the systemjs.config file, for ‘app’ keyword (refer the content below taken from the systemjs.config file) the folder is mapped to ‘app’ folder.
var map = {
'app': 'app', // 'dist',
'@angular': 'node_modules/@angular',
'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
'rxjs': 'node_modules/rxjs'
};
 
If we want to rename our ‘app’ (refer the content below, taken from the systemjs.config file), then we also need to modify in systemjs.config file. The default mapping is with the name ‘app’.
Next, in our code, when we reference the path as ‘@angular/core’, it will map the path to ‘node_modules/@angular/core’.

Step 2 - Defining Component

Now, Let us create our First Component and save the file with .ts as extension. For a file containing Component, the standard naming convention is someName.component.ts. Let us name our file as ‘app.component.ts’ and place it under 'app' folder
Let us name the Class as AppComponent
In this class we write properties and methods required for our view or html page. The keyword ‘export’ makes the Component modular or say we can use this class in other files by importing this class name. The first Component of the application is also known as root Component
Next, we write Metadata of the Component above the Class AppComponent as,

Then, as the keyword ‘Component’ is defined in @angular/core module, we will add it’s reference as,
import {Component} from ‘@angular/core’;
So our code in app.component.ts looks like,
Remember the tag <my-app> in index.html page, When angular compiler comes across this tag, it replaces the tag’s content ‘Loading...’ with the content in ‘template’ <h1>Hello World, Welcome to Angular2</h1> and the same is displayed by browser as output.


Component = class + Metadata + template.

Step 3 - Initializing the Component in main.ts file

By this time, we have created index.html and app.component.ts files. Index.html contains the custom tag and its definition in app.component.ts file. Now let us bootstrap or initialize our root Component i.e AppComponent
For this, under the same ‘app’ folder, in the new file ‘main.ts’, we write
As bootstrap keyword is defined in @angular/platform-browser-dynamic and AppComponent class in ./app.component, we will import these files as below and place it on top position in the file.
import {bootstrap} from '@angular/platform-browser-dynamic';import {AppComponent} from './app.component';

Step 4 - Adding the references in Index.html file

So, we have created files, index.html, app.component.ts, main.ts file.
As this main.ts file contains initialization code, we add it’s reference in our index.html file as System.import(‘app/main’),
And as the System.import is defined in systemjs.config file, we will add the reference of this file in our index.html as below,

Let us Summarize

  1. We have used directive  <my-app>Loading… </my-app> in index.html
  2. Defined the <my-app> tag’s definition in Component in app.component.ts.
  3. Then to initialize the root Component i.e, AppComponent, we have written bootstrap(AppComponent)in main.ts file.
  4. And then, referenced this main.ts file in index.html as, System.import(‘app/main’). Also in index.html added, reference path to Systemjs.config.
In the figure, you can see the folder structure of our application which is highlighted with green border.

Step 5 - Executing our Application

Let us now execute our application.
From command prompt, navigate to our application folder (where index.html is present) or if you are using ‘Visual Code’ as editor, then you can right click on index.html file and the select the option ‘open with command prompt’ to directly navigate to required folder.

Then, on command prompt, execute the command npm start
This starts the services tsc (typescript compiler) and concurrently runs two services npm run in watch mode i.e ‘npm run tsc:w’ and npm run in lite mode i.e ‘npm run lite’. The service tsc -w compiles the typescript code into javascript and runs in watch mode, so that if any changes made to application and saved, it will automatically detects the changes and shows the updated output on browser (without the need of refreshing browser manually).

Check the screenshot to view npm services. If the code is free of errors, you can see the output as required and if your code contains any errors, the error messages will be thrown on command prompt and writes the error to npm log file.

Quelle:
https://www.codeproject.com/Articles/1173214/Getting-Started-with-Angular-Part
 

Angular 2

What is the Goal of Angular 2?

“Angular 2 is an open source JavaScript framework which simplifies binding code between JavaScript objects and HTML UI elements.”
Let us try to understand the above definition with simple sample code.
Below is a simple “Customer” function with “CustomerName” property. We have also created an object called as “Cust” which is of “Customer” class type.
function Customer() 
{
this.CustomerName = "AngularInterview";
}
var Cust = new Customer();
Now let us say in the above customer object we want to bind to a HTML text box called as “TxtCustomerName”. In other words when we change something in the HTML text box the customer object should get updated and when something is changed internally in the customer object the UI should get updated.
<input id="TxtCustomerName" onchange="UitoObject()" type="text" />
So in order to achieve this communication between UI to object developers end up writing functions as shown below. “UitoObject” function takes data from UI and sets it to the object while the other function “ObjecttoUI” takes data from the object and sets it to UI.
function UitoObject() 
{
Cust.CustomerName = $("#TxtCustomerName").val();
}
function ObjecttoUi()
{
$("#TxtCustomerName").val(Cust.CustomerName);
}
So if we analyze the above code visually it looks something as shown below. Your both functions are nothing but binding code logic which transfers data from UI to object and vice versa.
Binding Code
Now the same above code can be written in Angular as shown below. So now whatever you type in the textbox updates the “Customer” object and when the “Customer” object gets updated it also updates the UI.
<input type="text" />
In short if you now analyze the above code visually you end up with something as shown in the below figure.You have the VIEW which is in HTML, your MODEL objects which are javascript functions and the binding code in Angular.
Javascript Functions
Now that binding code have different vocabularies.
  • Some developers called it “ViewModel” because it connects the “Model” and the “View” .
  • Some call it “Presenter” because this logic is nothing but presentation logic.
  • Some term it has “Controller” because it controls how the view and the model will communicate.
To avoid this vocabulary confusion Angular team has termed this code as “Whatever”. It’s that “Whatever” code which binds the UI and the Model. That’s why you will hear lot of developers saying Angular implements “MVW” architecture.
So concluding the whole goal of Angular is Binding, Binding and Binding.

Pre-requisite for Angular 2 before you start

In my initial journey of learning Angular 2 I realized that Angular 2 by itself is easy to understand. But Angular 2 uses lot of JavaScript open sources and if you do not know these open sources Learning Angular 2 would become extremely difficult.
So we would recommend spending your some time going through the below videos and making notes around the same:-
Topic nameYouTube URL source
Node JShttps://www.youtube.com/watch?v=-LF_43_Mqnw
Type Scripthttps://www.youtube.com/watch?v=xqYD8QXJX9U
System JShttps://www.youtube.com/watch?v=nQGhdoIMKaM
Common JS concepthttps://www.youtube.com/watch?v=jN4IM5tp1SE

Quelle:
https://www.codeproject.com/Articles/1174685/Learn-Angular-step-by-step-for-Beginners-Lab 


 

Tippe für AngularJS



1.       Form Validation
a.       Um die Validation zu verwenden,müssen Sie die folgenden Schritte folgen:
                                                               i.      Geben einen „Name“, um Ihre Form
                                                             ii.      Markieren alle required Input Felder nach required
                                                            iii.      Überprüfen, ob das Formular überprüft wird oder nicht, durch Prüfen:
<input name="meinName" ng-model="meinName" required>
<span ng-show="meinForm.meinName.$touched && meinForm. meinName.$invalid">Der Name ist required.</span>

2.         Debugging von JS Projekten: 
a.        Mit ng-inspector für AngularJSund Chrome
 

b.      Ein weiteres Werkzeug, das sich in diesem Kontext sehr gut eignet und aktuell eine verbreitete Entwicklungsumgebung im Bereich AngularJS ist, $log
Der Hauptzweck dieses Dienstes ist die Fehlersuche und Fehlerbehebung zu vereinfachen.
angular.module('logExample', []).controller('LogController', ['$scope', '$log', function($scope, $log) {
    $scope.$log = $log;
….
 $log.info("info Data", data);
….
}]);
Als Ergebnis:


3.       Databinding (Two-Way)
Im grafischen Beispiel unten wird jedes Element des Arrays $scope.todos einem <li>-Element im DOM zugeordnet. Wird jetzt z.B. 'Staubsaugen' aus dem Array entfernt, wird diese Veränderung dem View gemeldet und auch dort entfernt. Das Template steht jederzeit als Blaupause bereit, um neue Elemente im View erzeugen und verändern zu können.
Der Vorteil dürfte offensichtlich sein. Die manuelle Synchronisation fällt weg und damit auch eine Menge Arbeit und fehleranfälliger Code.



4.         ng-Controller
Dieser Controller macht nichts weiter, als auf dem Scope Name den Wert AngularJShinzuzufügen.


Wie man sieht, existieren jetzt zwei Scopes. Das $rootScope, definiert durch ng-app und ein neues Scope, definiert durch ng-controller.