Showing posts with label angular. Show all posts
Showing posts with label angular. Show all posts

Wednesday, April 1, 2020

Angular Data-Binding

Data-binding is the core concept of Angular and used to define the communication between a component and the DOM. It is a technique to link your data to your view layer. In simple words, you can say that data binding is a communication between your typescript code of your component and your template which the user sees. It makes easy to define interactive applications without worrying about pushing and pulling data. Data binding can be either one-way data binding or two-way data binding.

Angular provides four types of data binding and they are different on the way of data flowing.
  1. String Interpolation
  2. Property Binding
  3. Event Binding
  4. Two-way binding

String interpolation/ Angular Expression
String Interpolation is a one-way data-binding technique which is used to output the data from a TypeScript code to HTML template (view). It uses the template expression in double curly braces to display the data from the component to the view.
For example:
{{ data }}
String interpolation adds the value of a property from the component:
Syntax:
<li>Name: {{ user.name }}</li>  
<li>Email: {{ user.email }}</li>  


Property Binding
Property Binding is also a one-way data-binding technique. In property binding, we bind a property of a DOM element to a field which is a defined property in our component TypeScript code.
For example:
<img [src]="imgUrl"/>
Syntax:
<input type="email" [value]="user.email">  


Event Binding
In Angular, event binding is used to handle the events raised from the DOM like button click, mouse move etc. When the DOM event happens (eg. click, change, keyup), it calls the specified method in the component. In the following example, the cookBacon() method from the component is called when the button is clicked:
For example:
<button (click)="cookBacon()"></button>  


Two-way Data Binding
We have seen that in one-way data binding any change in the template (view) was not be reflected in the component TypeScript code. To resolve this problem, Angular provides two-way data binding. The two-way binding has a feature to update data from component to view and vice-versa.
In two way data binding, property binding, and event binding are combined together.
Syntax:
[(ngModel)] = "[property of your component]"  


Note: For two way data binding, we have to enable the ngModel directive. It depends upon FormsModule in angular/forms package, so we have to add FormsModule in imports[] array in the AppModule.




Angular CLI | Angular Project Setup


Angular is a front-end framework that is used to create web applications. It uses typescript by default for creating logics and methods for a class but the browser doesn’t know typescript. Here webpack comes in the picture, webpack is used to compile these typescript files to JavaScript. In addition, there are so many configuration files you will need to run an angular project on your computer.


Angular CLI is a tool that does all these things for you in some simple commands. Angular CLI uses webpack behind to do all this process.

Note: Please make sure you have installed node and npm in your system. You can check your node version and npm version by using the following command:

node --version
npm --version


 Steps to Create your first application using angular CLI:
·       Step-1: Install angular cli
npm install - g @angular/cli


·       Step-2: Create new project by this command
Choose yes for routing option and, CSS or SCSS.
ng new myNewApp

·       Step-3: Go to your project directory
cd myNewApp


·       Step-4: Run server and see your application in action
ng serve --o


Introduction to directory structure:
·       e2e It contains the code related to automated testing purpose. For example, if on a certain page you are calling a REST API then what should be the return status code, whether it is acceptable or not etc.
·       node_modules It saves all the dev dependencies (used only at development time) and dependencies (used for development as well as needed in production time), any new dependency when added to project it is automatically saved to this folder.
·      src This directory contains all of our work related to project i.e. creating components, creating services, adding CSS to the respective page, etc.
·      package.json This file stores the information about the libraries added and used in the project with their specified version installed. Whenever a new library is added to the project it’s name and version is added to the dependencies in package.json.


Other files: As a beginner you don’t need these files at this time, don’t bother about that. These all are used for editor configurations and information needed at compile time. The builtin webpack in angular CLI manages all for you.
Inside src folder:
·       index.html This is the entry point for the application, app-root tag is the entry point of the application on this single page application, on this page angular will add or remove the content from the DOM or will add new content to the DOM. Base href=”/” is important for routing purposes.

<!DOCTYPE HTML>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>MyNewApp</title>
        <base href="/">
     <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="icon" typw="image/x-icon" href="favison.ico">
    </head>
    <body>
        <app-root></app-root>
    </body>
</html>
·     style.scss This file is the global stylesheet you can add that CSS classes or selectors which are common to many components, for example, you can import custom fonts, import bootstrap.css, etc.
·       assets It contains the js images, fonts, icons and many other files for your project.
Inside app folder:
·       app.module.ts An angular project is a composite of so many other modules in order to create an application you have to create a root module for your application in the hierarchy. This app.module.ts file is that. If you want to add more modules at the root level, you can add.
·   declarations It is the reference of the array to store its components. The app component is the default component that is generated when a project is created. You have to add all your component’s reference to this array to make them available in the project.
·    imports If you want to add any module whether angular or you have to add it to imports array to make them available in the whole project.
·       providers If you will create any service for your application then you will inject it into your project through this provider array. Service injected to a module is available to it and it’s child module in the project hierarchy.
·    bootstrap This has reference to the default component created, i.e., AppComponent
·       app.component.html Edit this file to make changes to the page. You can edit this file as an HTML file. Work directly with div or any other tag used inside body tags, these are components and do not add HTML head body tags.

<h1>
    Hello world
</h1>
 <div>
    <p>
        This is my First Angular app.
    </p>
</div>
·      app.component.spec.ts These are automatically generated files which contain unit tests for source component.
·       app.component.ts You can do the processing of the HTML structure in the .ts file. The processing will include activities such as connecting to the database, interacting with other components, routing, services, etc.
·      app.component.scss Here you can add CSS for your component. You can write scss which further compiled to CSS by a transpiler.

More commands that you will need while working on the project:
ng generate component component_name
ng generate service service_name
ng generate directive directive_name


Angular Architecture


Angular is a platform and framework for building client applications in HTML and TypeScript. Typescript is a superset of Javascript. Angular is written in TypeScript. It implements core and optional functionality as a set of TypeScript libraries that you import into your apps. The pioneer building blocks of the Angular application are NgModules, which provide the compilation context for components.

We can identify the following main building blocks of an Angular Application.
1.   Modules
2.   Components
3.   Templates
4.   Metadata
5.   Data binding
6.   Directives
7.   Services
8.   Dependency Injection

A set of NgModules defines the angular appand it always has at least a root module that enables bootstrapping, and many more feature modules.
  1. Components define Template views
  2. Components use services

The Angular Module (NgModules) helps us to organize an application into connected blocks of functionality.
Angular Modules
Every Angular app has a root module, conventionally named AppModule, which provides the bootstrap mechanism that launches the application. An app typically contains many functional modules.
// 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';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
If we want to use another custom Angular module, then we need to register that module inside the app.module.ts file. Organizing your code into distinct functional modules helps in managing the development of complex applications, and in designing for reusability.
Angular  Components
Every Angular project has at least one component, the root component and root component connects the component hierarchy with a page document object model (DOM). Each component defines the class that contains application data and logic, and it is associated with the HTML template that defines the view to be displayed in a target app.
The @Component decorator identifies the class immediately below it as the component and provides the template and related component-specific metadata.
// app.component.ts

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
Angular  Templates
The angular template combines the HTML with Angular markup that can modify HTML elements before they are displayed. Template directives provide program logic, and binding markup connects your application data and the DOM. There are two types of data binding.
  • Event binding lets your app respond to user input in the target environment by updating your application data.
  • Property binding lets you interpolate values that are computed from your application data into the HTML.
<div style="text-align:center">
  <h1>
    {{2 | power: 5}}
  </h1>
</div>
In the above HTML file, we have used a template. We have also used the pipe inside the template to transform the values to the desired output.
Angular  Metadata
Metadata is used to decorate the class so that it can configure the expected behavior of a class. Decorators are the core concept when developing with Angular (versions 2 and above). The user can use metadata to a class to tell Angular app that AppComponent is the component. Metadata can be attached to the TypeScript using the decorator.
// app.component.ts

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
@Component is a decorator which makes use of configuration object to create the component and its view.
Angular  Data Binding
Angular allows defining communication between a component and the DOM, making it very easy to define interactive applications without worrying about pulling and pushing the data.
From the Component to the DOM
Interpolation: {{ value }}: Interpolation adds the value of the property from the component.
<p>Name: {{ student.name }}</p>
<p>College: {{ student.college }}</p>
Property binding: [property]=”value”
With property binding, a value is passed from a component to a specified property, which can often be a simple html attribute.
<input type="text" [value]="student.name" />
<input type="text" [value]="student.college" />
Angular  Directives
An Angular component isn’t more than a directive with the template. When we say that components are the building blocks of Angular applications, we are saying that directives are the building blocks of Angular projects. Let us use built-in Angular directive like ngClass, which is a better example of the existing Angular attribute directive.
<p [ngClass]="{'coffee'=true, 'red'=false}">
    Angular 7 Directives Example
</p>

<style>
    .coffee{color: coffee}
    .red{color: red}
</style>
Here, based on the [ngClass] directive’s value, the text has color. In our example, the text will be coffee because it is true.
Angular  Services
For data or logic that isn’t associated with a specific view, and that you want to share across components, you create a service class. The @Injectable decorator immediately precedes the service class definition. The decorator provides the metadata that allows your service to be injected into client components as a dependency. Angular distinguishes components from services to increase modularity and reusability. By separating a component’s view-related functionality from other kinds of processing, you can make your component classes lean and efficient.
Angular  Dependency Injection
Dependency injection (DI) lets you keep your component classes lean and efficient. DI does not fetch data from a server, validate the user input, or log directly to the console instead they delegate such tasks to the services. DI is wired into a Angular framework and used everywhere to provide new components with the services or other things they need. Components consume services; that is, you can inject a service into a component, giving the component access to that service class.