Discuss Angular 4 ”; Previous Next Angular 4 is a JavaScript framework for building web applications and apps in JavaScript, html, and TypeScript, which is a superset of JavaScript. Angular provides built-in features for animation, http service, and materials which in turn has features such as auto-complete, navigation, toolbar, menus, etc. The code is written in TypeScript, which compiles to JavaScript and displays the same in the browser. Print Page Previous Next Advertisements ”;
Category: angular4
Angular 4 – Materials
Angular 4 – Materials ”; Previous Next Materials offer a lot of built-in modules for your project. Features such as autocomplete, datepicker, slider, menus, grids, and toolbar are available for use with materials in Angular 4. To use materials, we need to import the package. Angular 2 also has all the above features but they are available as part of the @angular/core module. Angular 4 has come up with a separate module @angular/materials.. This helps the user to import the required materials. To start using materials, you need to install two packages – materials and cdk. Material components depend on the animation module for advanced features, hence you need the animation package for the same, i.e., @angular/animations. The package has already been updated in the previous chapter. npm install –save @angular/material @angular/cdk Let us now see the package.json. @angular/material and @angular/cdk are installed. { “name”: “angularstart”, “version”: “0.0.0”, “license”: “MIT”, “scripts”: { “ng”: “ng”, “start”: “ng serve”, “build”: “ng build”, “test”: “ng test”, “lint”: “ng lint”, “e2e”: “ng e2e” }, “private”: true, “dependencies”: { “@angular/animations”: “^4.0.0”, “@angular/cdk”: “^2.0.0-beta.8”, “@angular/common”: “^4.0.0”, “@angular/compiler”: “^4.0.0”, “@angular/core”: “^4.0.0”, “@angular/forms”: “^4.0.0”, “@angular/http”: “^4.0.0”, “@angular/material”: “^2.0.0-beta.8”, “@angular/platform-browser”: “^4.0.0”, “@angular/platform-browser-dynamic”: “^4.0.0”, “@angular/router”: “^4.0.0”, “core-js”: “^2.4.1”, “rxjs”: “^5.1.0”, “zone.js”: “^0.8.4” }, “devDependencies”: { “@angular/cli”: “1.2.0”, “@angular/compiler-cli”: “^4.0.0”, “@angular/language-service”: “^4.0.0”, “@types/jasmine”: “~2.5.53”, “@types/jasminewd2”: “~2.0.2”, “@types/node”: “~6.0.60”, “codelyzer”: “~3.0.1”, “jasmine-core”: “~2.6.2”, “jasmine-spec-reporter”: “~4.1.0”, “karma”: “~1.7.0”, “karma-chrome-launcher”: “~2.1.1”, “karma-cli”: “~1.0.1”, “karma-coverage-istanbul-reporter”: “^1.2.1”, “karma-jasmine”: “~1.1.0”, “karma-jasmine-html-reporter”: “^0.2.2”, “protractor”: “~5.1.2”, “ts-node”: “~3.0.4”, “tslint”: “~5.3.2”, “typescript”: “~2.3.3″ } } We have highlighted the packages that are installed to work with materials. We will now import the modules in the parent module – app.module.ts as shown below. import { BrowserModule } from ”@angular/platform-browser”; import { NgModule } from ”@angular/core”; import { BrowserAnimationsModule } from ”@angular/platform-browser/animations”; import { MdButtonModule, MdMenuModule, MdSidenavModule } from ”@angular/material”; import { FormsModule } from ”@angular/forms”; import { AppComponent } from ”./app.component”; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, BrowserAnimationsModule, MdButtonModule, MdMenuModule, FormsModule, MdSidenavModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } In the above file, we have imported the following modules from @angular/materials. import { MdButtonModule, MdMenuModule, MdSidenavModule } from ”@angular/material”; And the same is used in the imports array as shown below − imports: [ BrowserModule, BrowserAnimationsModule, MdButtonModule, MdMenuModule, FormsModule, MdSidenavModule ] The app.component.ts is as shown below − import { Component } from ”@angular/core”; @Component({ selector: ”app-root”, templateUrl: ”./app.component.html”, styleUrls: [”./app.component.css”] }) export class AppComponent { myData: Array<any>; constructor() {} } Let us now add the material in app.component.html. <button md-button [mdMenuTriggerFor]=”menu”>Menu</button> <md-menu #menu=”mdMenu”> <button md-menu-item> File </button> <button md-menu-item> Save As </button> </md-menu> <md-sidenav-container class=”example-container”> <md-sidenav #sidenav class=”example-sidenav”> Angular 4 </md-sidenav> <div class=”example-sidenav-content”> <button type=”button” md-button (click)=”sidenav.open()”> Open sidenav </button> </div> </md-sidenav-container> In the above file, we have added Menu and SideNav. Menu To add menu, <md-menu></md-menu> is used. The file and Save As items are added to the button under md-menu. There is a main button added Menu. The reference of the same is given the <md-menu> by using [mdMenuTriggerFor]=”menu” and using the menu with # in <md-menu>. SideNav To add sidenav, we need <md-sidenav-container></md-sidenav-container>. <md-sidenav></md-sidenav> is added as a child to the container. There is another div added, which triggers the sidenav by using (click)=”sidenav.open()”. Following is the display of the menu and the sidenav in the browser − Upon clicking opensidenav, it shows the side bar as shown below − Upon clicking Menu, you will get two items File and Save As as shown below − Let us now add a datepicker using materials. To add a datepicker, we need to import the modules required to show the datepicker. In app.module.ts, we have imported the following module as shown below for datepicker. import { BrowserModule } from ”@angular/platform-browser”; import { NgModule } from ”@angular/core”; import { BrowserAnimationsModule } from ”@angular/platform-browser/animations”; import { MdDatepickerModule, MdInputModule, MdNativeDateModule } from ”@angular/material”; import { FormsModule } from ”@angular/forms”; import { AppComponent } from ”./app.component”; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, BrowserAnimationsModule, FormsModule, MdDatepickerModule, MdInputModule, MdNativeDateModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } Here, we have imported modules such as MdDatepickerModule, MdInputModule, and MdNativeDateModule. Now, the app.component.ts is as shown below − import { Component } from ”@angular/core”; @Component({ selector: ”app-root”, templateUrl: ”./app.component.html”, styleUrls: [”./app.component.css”] }) export class AppComponent { myData: Array<any>; constructor() {} } The app.component.html is as shown below − <md-input-container> <input mdInput [mdDatepicker]=”picker” placeholder=”Choose a date”> <button mdSuffix [mdDatepickerToggle]=”picker”></button> </md-input-container> <md-datepicker #picker></md-datepicker> This is how the datepicker is displayed in the browser − Print Page Previous Next Advertisements ”;
Angular 4 – Animations
Angular 4 – Animations ”; Previous Next Animations add a lot of interaction between the html elements. Animation was also available with Angular2. The difference with Angular 4 is that animation is no more a part of the @angular/core library, but is a separate package that needs to be imported in app.module.ts. To start with, we need to import the library as follows − import { BrowserAnimationsModule } from ”@angular/platform-browser/animations”; The BrowserAnimationsModule needs to be added to the import array in app.module.ts as shown below − app.module.ts import { BrowserModule } from ”@angular/platform-browser”; import { NgModule } from ”@angular/core”; import { BrowserAnimationsModule } from ”@angular/platform-browser/animations”; import { AppComponent } from ”./app.component”; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, BrowserAnimationsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } In app.component.html, we have added the html elements, which are to be animated. <div> <button (click)=”animate()”>Click Me</button> <div [@myanimation] = “state” class=”rotate”> <img src=”assets/images/img.png” width=”100″ height=”100″> </div> </div> For the main div, we have added a button and a div with an image. There is a click event for which the animate function is called. And for the div, the @myanimation directive is added and given the value as state. Let us now see the app.component.ts where the animation is defined. import { Component } from ”@angular/core”; import { trigger, state, style, transition, animate } from ”@angular/animations”; @Component({ selector: ”app-root”, templateUrl: ”./app.component.html”, styleUrls: [”./app.component.css”], styles:[` div{ margin: 0 auto; text-align: center; width:200px; } .rotate{ width:100px; height:100px; border:solid 1px red; } `], animations: [ trigger(”myanimation”,[ state(”smaller”,style({ transform : ”translateY(100px)” })), state(”larger”,style({ transform : ”translateY(0px)” })), transition(”smaller <=> larger”,animate(”300ms ease-in”)) ]) ] }) export class AppComponent { state: string = “smaller”; animate() { this.state= this.state == ”larger” ? ”smaller” : ”larger”; } } We have to import the animation function that is to be used in the .ts file as shown above. import { trigger, state, style, transition, animate } from ”@angular/animations”; Here we have imported trigger, state, style, transition, and animate from @angular/animations. Now, we will add the animations property to the @Component () decorator − animations: [ trigger(”myanimation”,[ state(”smaller”,style({ transform : ”translateY(100px)” })), state(”larger”,style({ transform : ”translateY(0px)” })), transition(”smaller <=> larger”,animate(”300ms ease-in”)) ]) ] Trigger defines the start of the animation. The first param to it is the name of the animation to be given to the html tag to which the animation needs to be applied. The second param are the functions we have imported – state, transition, etc. The state function involves the animation steps, which the element will transition between. Right now we have defined two states, smaller and larger. For smaller state, we have given the style transform:translateY(100px) and transform:translateY(100px). Transition function adds animation to the html element. The first argument takes the states, i.e., start and end; the second argument accepts the animate function. The animate function allows you to define the length, delay, and easing of a transition. Let us now see the .html file to see how the transition function works <div> <button (click)=”animate()”>Click Me</button> <div [@myanimation] = “state” class=”rotate”> <img src=”assets/images/img.png” width=”100″ height=”100″> </div> </div> There is a style property added in the @component directive, which centrally aligns the div. Let us consider the following example to understand the same − styles:[` div{ margin: 0 auto; text-align: center; width:200px; } .rotate{ width:100px; height:100px; border:solid 1px red; } `], Here, a special character [“] is used to add styles to the html element, if any. For the div, we have given the animation name defined in the app.component.ts file. On the click of a button it calls the animate function, which is defined in the app.component.ts file as follows − export class AppComponent { state: string = “smaller”; animate() { this.state= this.state == ‘larger’? ”smaller” : ”larger”; } } The state variable is defined and is given the default value as smaller. The animate function changes the state on click. If the state is larger, it will convert to smaller; and if smaller, it will convert to larger. This is how the output in the browser (http://localhost:4200/) will look like − Upon clicking the Click Me button, the position of the image is changed as shown in the following screenshot − The transform function is applied in the y direction, which is changed from 0 to 100px when the Click Me button is clicked. The image is stored in the assets/images folder. Print Page Previous Next Advertisements ”;
Angular 4 – Module
Angular 4 – Module ”; Previous Next Module in Angular refers to a place where you can group the components, directives, pipes, and services, which are related to the application. In case you are developing a website, the header, footer, left, center and the right section become part of a module. To define module, we can use the NgModule. When you create a new project using the Angular –cli command, the ngmodule is created in the app.module.ts file by default and it looks as follows − import { BrowserModule } from ”@angular/platform-browser”; import { NgModule } from ”@angular/core”; import { AppComponent } from ”./app.component”; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } The NgModule needs to be imported as follows − import { NgModule } from ”@angular/core”; The structure for the ngmodule is as shown below − @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule ], providers: [], bootstrap: [AppComponent] }) It starts with @NgModule and contains an object which has declarations, import s, providers and bootstrap. Declaration It is an array of components created. If any new component gets created, it will be imported first and the reference will be included in declarations as shown below − declarations: [ AppComponent, NewCmpComponent ] Import It is an array of modules required to be used in the application. It can also be used by the components in the Declaration array. For example, right now in the @NgModule we see the Browser Module imported. In case your application needs forms, you can include the module as follows − import { FormsModule } from ”@angular/forms”; The import in the @NgModule will be like the following − imports: [ BrowserModule, FormsModule ] Providers This will include the services created. Bootstrap This includes the main app component for starting the execution. Print Page Previous Next Advertisements ”;
Angular 4 – Data Binding
Angular 4 – Data Binding ”; Previous Next Data Binding is available right from AngularJS, Angular 2 and is now available in Angular 4 as well. We use curly braces for data binding – {{}}; this process is called interpolation. We have already seen in our previous examples how we declared the value to the variable title and the same is printed in the browser. The variable in the app.component.html file is referred as {{title}} and the value of title is initialized in the app.component.ts file and in app.component.html, the value is displayed. Let us now create a dropdown of months in the browser. To do that , we have created an array of months in app.component.ts as follows − import { Component } from ”@angular/core”; @Component({ selector: ”app-root”, templateUrl: ”./app.component.html”, styleUrls: [”./app.component.css”] }) export class AppComponent { title = ”Angular 4 Project!”; // declared array of months. months = [“January”, “Feburary”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”]; } The month’s array that is shown above is to be displayed in a dropdown in the browser. For this, we will use the following line of code − <!–The content below is only a placeholder and can be replaced. –> <div style=”text-align:center”> <h1> Welcome to {{title}}. </h1> </div> <div> Months : <select> <option *ngFor=”let i of months”>{{i}}</option> </select> </div> We have created the normal select tag with option. In option, we have used the for loop. The for loop is used to iterate over the months’ array, which in turn will create the option tag with the value present in the months. The syntax for in Angular is *ngFor = “let I of months” and to get the value of months we are displaying it in {{i}}. The two curly brackets help with data binding. You declare the variables in your app.component.ts file and the same will be replaced using the curly brackets. Let us see the output of the above month’s array in the browser The variable that is set in the app.component.ts can be bound with the app.component.html using the curly brackets; for example, {{}}. Let us now display the data in the browser based on condition. Here, we have added a variable and assigned the value as true. Using the if statement, we can hide/show the content to be displayed. Example import { Component } from ”@angular/core”; @Component({ selector: ”app-root”, templateUrl: ”./app.component.html”, styleUrls: [”./app.component.css”] }) export class AppComponent { title = ”Angular 4 Project!”; //array of months. months = [“January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”]; isavailable = true; //variable is set to true } <!–The content below is only a placeholder and can be replaced.–> <div style = “text-align:center”> <h1> Welcome to {{title}}. </h1> </div> <div> Months : <select> <option *ngFor = “let i of months”>{{i}}</option> </select> </div> <br/> <div> <span *ngIf = “isavailable”>Condition is valid.</span> //over here based on if condition the text condition is valid is displayed. If the value of isavailable is set to false it will not display the text. </div> Output Let us try the above example using the IF THEN ELSE condition. Example import { Component } from ”@angular/core”; @Component({ selector: ”app-root”, templateUrl: ”./app.component.html”, styleUrls: [”./app.component.css”] }) export class AppComponent { title = ”Angular 4 Project!”; //array of months. months = [“January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”]; isavailable = false; } In this case, we have made the isavailable variable as false. To print the else condition, we will have to create the ng-template as follows − <ng-template #condition1>Condition is invalid</ng-template> The full code looks like this − <!–The content below is only a placeholder and can be replaced.–> <div style=”text-align:center”> <h1> Welcome to {{title}}. </h1> </div> <div> Months : <select> <option *ngFor=”let i of months”>{{i}}</option> </select> </div> <br/> <div> <span *ngIf=”isavailable; else condition1″>Condition is valid.</span> <ng-template #condition1>Condition is invalid</ng-template> </div> If is used with the else condition and the variable used is condition1. The same is assigned as an id to the ng-template, and when the available variable is set to false the text Condition is invalid is displayed. The following screenshot shows the display in the browser. Let us now use the if then else condition. import { Component } from ”@angular/core”; @Component({ selector: ”app-root”, templateUrl: ”./app.component.html”, styleUrls: [”./app.component.css”] }) export class AppComponent { title = ”Angular 4 Project!”; //array of months. months = [“January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”]; isavailable = true; } Now, we will make the variable isavailable as true. In the html, the condition is written in the following way − <!–The content below is only a placeholder and can be replaced.–> <div style=”text-align:center”> <h1> Welcome to {{title}}. </h1> </div> <div> Months : <select> <option *ngFor=”let i of months”>{{i}}</option> </select> </div> <br/> <div> <span *ngIf=”isavailable; then condition1 else condition2″>Condition is valid.</span> <ng-template #condition1>Condition is valid</ng-template> <ng-template #condition2>Condition is invalid</ng-template> </div> If the variable is true, then condition1, else condition2. Now, two templates are created with id #condition1 and #condition2. The display in the browser is as follows − Print Page Previous Next Advertisements ”;
Angular 4 – Forms
Angular 4 – Forms ”; Previous Next In this chapter, we will see how forms are used in Angular 4. We will discuss two ways of working with forms – template driven form and model driven forms. Template Driven Form With a template driven form, most of the work is done in the template; and with the model driven form, most of the work is done in the component class. Let us now consider working on the Template driven form. We will create a simple login form and add the email id, password and submit the button in the form. To start with, we need to import to FormsModule from @angular/core which is done in app.module.ts as follows − import { BrowserModule } from ”@angular/platform-browser”; import { NgModule } from ”@angular/core”; import { RouterModule} from ”@angular/router”; import { HttpModule } from ”@angular/http”; import { FormsModule } from ”@angular/forms”; import { AppComponent } from ”./app.component”; import { MyserviceService } from ”./myservice.service”; import { NewCmpComponent } from ”./new-cmp/new-cmp.component”; import { ChangeTextDirective } from ”./change-text.directive”; import { SqrtPipe } from ”./app.sqrt”; @NgModule({ declarations: [ SqrtPipe, AppComponent, NewCmpComponent, ChangeTextDirective ], imports: [ BrowserModule, HttpModule, FormsModule, RouterModule.forRoot([ {path: ”new-cmp”,component: NewCmpComponent} ]) ], providers: [MyserviceService], bootstrap: [AppComponent] }) export class AppModule { } So in app.module.ts, we have imported the FormsModule and the same is added in the imports array as shown in the highlighted code. Let us now create our form in the app.component.html file. <form #userlogin = “ngForm” (ngSubmit) = “onClickSubmit(userlogin.value)” > <input type = “text” name = “emailid” placeholder = “emailid” ngModel> <br/> <input type = “password” name = “passwd” placeholder = “passwd” ngModel> <br/> <input type = “submit” value = “submit”> </form> We have created a simple form with input tags having email id, password and the submit button. We have assigned type, name, and placeholder to it. In template driven forms, we need to create the model form controls by adding the ngModel directive and the name attribute. Thus, wherever we want Angular to access our data from forms, add ngModel to that tag as shown above. Now, if we have to read the emailid and passwd, we need to add the ngModel across it. If you see, we have also added the ngForm to the #userlogin. The ngForm directive needs to be added to the form template that we have created. We have also added function onClickSubmit and assigned userlogin.value to it. Let us now create the function in the app.component.ts and fetch the values entered in the form. 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 { title = ”Angular 4 Project!”; todaydate; componentproperty; constructor(private myservice: MyserviceService) { } ngOnInit() { this.todaydate = this.myservice.showTodayDate(); } onClickSubmit(data) { alert(“Entered Email id : ” + data.emailid); } } In the above app.component.ts file, we have defined the function onClickSubmit. When you click on the form submit button, the control will come to the above function. This is how the browser is displayed − The form looks like as shown below. Let us enter the data in it and in the submit function, the email id is already entered. The email id is displayed at the bottom as shown in the above screenshot. Model Driven Form In the model driven form, we need to import the ReactiveFormsModule from @angular/forms and use the same in the imports array. There is a change which goes in app.module.ts. import { BrowserModule } from ”@angular/platform-browser”; import { NgModule } from ”@angular/core”; import { RouterModule} from ”@angular/router”; import { HttpModule } from ”@angular/http”; import { ReactiveFormsModule } from ”@angular/forms”; import { AppComponent } from ”./app.component”; import { MyserviceService } from ”./myservice.service”; import { NewCmpComponent } from ”./new-cmp/new-cmp.component”; import { ChangeTextDirective } from ”./change-text.directive”; import { SqrtPipe } from ”./app.sqrt”; @NgModule({ declarations: [ SqrtPipe, AppComponent, NewCmpComponent, ChangeTextDirective ], imports: [ BrowserModule, HttpModule, ReactiveFormsModule, RouterModule.forRoot([ { path: ”new-cmp”, component: NewCmpComponent } ]) ], providers: [MyserviceService], bootstrap: [AppComponent] }) export class AppModule { } In app.component.ts, we need to import a few modules for the model driven form. For example, import { FormGroup, FormControl } from ”@angular/forms”. import { Component } from ”@angular/core”; import { MyserviceService } from ”./myservice.service”; import { FormGroup, FormControl } from ”@angular/forms”; @Component({ selector: ”app-root”, templateUrl: ”./app.component.html”, styleUrls: [”./app.component.css”] }) export class AppComponent { title = ”Angular 4 Project!”; todaydate; componentproperty; emailid; formdata; constructor(private myservice: MyserviceService) { } ngOnInit() { this.todaydate = this.myservice.showTodayDate(); this.formdata = new FormGroup({ emailid: new FormControl(“[email protected]”), passwd: new FormControl(“abcd1234″) }); } onClickSubmit(data) {this.emailid = data.emailid;} } The variable formdata is initialized at the start of the class and the same is initialized with FormGroup as shown above. The variables emailid and passwd are initialized with default values to be displayed in the form. You can keep it blank in case you want to. This is how the values will be seen in the form UI. We have used formdata to initialize the form values; we need to use the same in the form UI app.component.html. <div> <form [formGroup]=”formdata” (ngSubmit) = “onClickSubmit(formdata.value)” > <input type=”text” class=”fortextbox” name=”emailid” placeholder=”emailid” formControlName=”emailid”> <br/> <input type=”password” class=”fortextbox” name=”passwd” placeholder=”passwd” formControlName=”passwd”> <br/> <input type=”submit” class=”forsubmit” value=”Log In”> </form> </div> <p> Email entered is : {{emailid}} </p> In the .html file, we have used formGroup in square bracket for the form; for example, [formGroup]=”formdata”. On submit, the function is called onClickSubmit for which formdata.value is passed. The input tag formControlName is used. It is given a value that we have used in the app.component.ts file. On clicking submit, the control will pass to the function onClickSubmit, which is defined in the app.component.ts file. On clicking Login, the value will be displayed as shown in the above screenshot. Form Validation Let us now discuss form validation using model driven form. You can use the built-in form validation or also use the custom validation approach. We will use both the approaches in the form. We will continue with the same example that
Angular 4 – Useful Resources
Angular 4 – Useful Resources ”; Previous Next The following resources contain additional information on Angular 4. Please use them to get more in-depth knowledge on this topic. Useful Video Courses Angular – The Complete Course 14 Lectures 48 mins Ganesh Kavhar More Detail Angular JS Full Stack: Create and Host Listing/Classified Site 59 Lectures 4 hours Jay R More Detail Full-Stack web app development with Angular 12, .NET Core Web API & Mongo DB Most Popular 20 Lectures 49 mins Vinay Kumar More Detail Angular 12, .NET Core Web API & Microsoft SQL Full Stack Web Development 21 Lectures 55 mins Vinay Kumar More Detail Angular 12, .NET Core Web API and MySQL Web Development 21 Lectures 51 mins Vinay Kumar More Detail Angular 12, .NET Core Web API & PostgreSQL Full Stack Web Development 5 Lectures 51 mins Vinay Kumar More Detail Print Page Previous Next Advertisements ”;
Angular 4 – Http Service
Angular 4 – Http Service ”; Previous Next Http Service will help us fetch external data, post to it, etc. We need to import the http module to make use of the http service. Let us consider an example to understand how to make use of the http service. To start using the http service, we need to import the module in app.module.ts as shown below − import { BrowserModule } from ”@angular/platform-browser”; import { NgModule } from ”@angular/core”; import { BrowserAnimationsModule } from ”@angular/platform-browser/animations”; import { HttpModule } from ”@angular/http”; import { AppComponent } from ”./app.component”; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, BrowserAnimationsModule, HttpModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } If you see the highlighted code, we have imported the HttpModule from @angular/http and the same is also added in the imports array. Let us now use the http service in the app.component.ts. import { Component } from ”@angular/core”; import { Http } from ”@angular/http”; import ”rxjs/add/operator/map”; @Component({ selector: ”app-root”, templateUrl: ”./app.component.html”, styleUrls: [”./app.component.css”] }) export class AppComponent { constructor(private http: Http) { } ngOnInit() { this.http.get(“http://jsonplaceholder.typicode.com/users”). map((response) ⇒ response.json()). subscribe((data) ⇒ console.log(data)) } } Let us understand the code highlighted above. We need to import http to make use of the service, which is done as follows − import { Http } from ”@angular/http”; In the class AppComponent, a constructor is created and the private variable http of type Http. To fetch the data, we need to use the get API available with http as follows this.http.get(); It takes the url to be fetched as the parameter as shown in the code. We will use the test url – https://jsonplaceholder.typicode.com/users to fetch the json data. Two operations are performed on the fetched url data map and subscribe. The Map method helps to convert the data to json format. To use the map, we need to import the same as shown below − import ”rxjs/add/operator/map”; Once the map is done, the subscribe will log the output in the console as shown in the browser − If you see, the json objects are displayed in the console. The objects can be displayed in the browser too. For the objects to be displayed in the browser, update the codes in app.component.html and app.component.ts as follows − import { Component } from ”@angular/core”; import { Http } from ”@angular/http”; import ”rxjs/add/operator/map”; @Component({ selector: ”app-root”, templateUrl: ”./app.component.html”, styleUrls: [”./app.component.css”] }) export class AppComponent { constructor(private http: Http) { } httpdata; ngOnInit() { this.http.get(“http://jsonplaceholder.typicode.com/users”). map( (response) ⇒ response.json() ). subscribe( (data) ⇒ {this.displaydata(data);} ) } displaydata(data) {this.httpdata = data;} } In app.component.ts, using the subscribe method we will call the display data method and pass the data fetched as the parameter to it. In the display data method, we will store the data in a variable httpdata. The data is displayed in the browser using for over this httpdata variable, which is done in the app.component.html file. <ul *ngFor = “let data of httpdata”> <li>Name : {{data.name}} Address: {{data.address.city}}</li> </ul> The json object is as follows − { “id”: 1, “name”: “Leanne Graham”, “username”: “Bret”, “email”: “[email protected]”, “address”: { “street”: “Kulas Light”, “suite”: “Apt. 556”, “city”: “Gwenborough”, “zipcode”: “92998-3874”, “geo”: { “lat”: “-37.3159”, “lng”: “81.1496” } }, “phone”: “1-770-736-8031 x56442”, “website”: “hildegard.org”, “company”: { “name”: “Romaguera-Crona”, “catchPhrase”: “Multi-layered client-server neural-net”, “bs”: “harness real-time e-markets” } } The object has properties such as id, name, username, email, and address that internally has street, city, etc. and other details related to phone, website, and company. Using the for loop, we will display the name and the city details in the browser as shown in the app.component.html file. This is how the display is shown in the browser − Let us now add the search parameter, which will filter based on specific data. We need to fetch the data based on the search param passed. Following are the changes done in app.component.html and app.component.ts files − app.component.ts import { Component } from ”@angular/core”; import { Http } from ”@angular/http”; import ”rxjs/add/operator/map”; @Component({ selector: ”app-root”, templateUrl: ”./app.component.html”, styleUrls: [”./app.component.css”] }) export class AppComponent { title = ”app”; searchparam = 2; jsondata; name; constructor(private http: Http) { } ngOnInit() { this.http.get(“http://jsonplaceholder.typicode.com/users?id=”+this.searchparam). map( (response) ⇒ response.json() ). subscribe((data) ⇒ this.converttoarray(data)) } converttoarray(data) { console.log(data); this.name = data[0].name; } } For the get api, we will add the search param id = this.searchparam. The searchparam is equal to 2. We need the details of id=2 from the json file. app.component.html {{name}} This is how the browser is displayed − We have consoled the data in the browser, which is received from the http. The same is displayed in the browser console. The name from the json with id=2 is displayed in the browser. Print Page Previous Next Advertisements ”;
Angular 4 – Templates
Angular 4 – Templates ”; Previous Next Angular 4 uses the <ng-template> as the tag instead of <template> which is used in Angular2. The reason Angular 4 changed <template> to <ng-template> is because there is a name conflict between the <template> tag and the html <template> standard tag. It will deprecate completely going ahead. This is one of the major changes in Angular 4. Let us now use the template along with the if else condition and see the output. app.component.html <!–The content below is only a placeholder and can be replaced.–> <div style = “text-align:center”> <h1> Welcome to {{title}}. </h1> </div> <div> Months : <select (change) = “changemonths($event)” name = “month”> <option *ngFor = “let i of months”>{{i}}</option> </select> </div> <br/> <div> <span *ngIf = “isavailable;then condition1 else condition2”>Condition is valid.</span> <ng-template #condition1>Condition is valid from template</ng-template> <ng-template #condition2>Condition is invalid from template</ng-template> </div> <button (click) = “myClickFunction($event)”>Click Me</button> For the Span tag, we have added the if statement with the else condition and will call template condition1, else condition2. The templates are to be called as follows − <ng-template #condition1>Condition is valid from template</ng-template> <ng-template #condition2>Condition is invalid from template</ng-template> If the condition is true, then the condition1 template is called, otherwise condition2. app.component.ts import { Component } from ”@angular/core”; @Component({ selector: ”app-root”, templateUrl: ”./app.component.html”, styleUrls: [”./app.component.css”] }) export class AppComponent { title = ”Angular 4 Project!”; //array of months. months = [“January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”]; isavailable = false; myClickFunction(event) { this.isavailable = false; } changemonths(event) { alert(“Changed month from the Dropdown”); console.log(event); } } The output in the browser is as follows − The variable isavailable is false so the condition2 template is printed. If you click the button, the respective template will be called. If you inspect the browser, you will see that you never get the span tag in the dom. The following example will help you understand the same. If you inspect the browser, you will see that the dom does not have the span tag. It has the Condition is invalid from template in the dom. The following line of code in html will help us get the span tag in the dom. <!–The content below is only a placeholder and can be replaced.–> <div style = “text-align:center”> <h1> Welcome to {{title}}. </h1> </div> <div> Months : <select (change) = “changemonths($event)” name = “month”> <option *ngFor = “let i of months”>{{i}}</option> </select> </div> <br/> <div> <span *ngIf = “isavailable; else condition2″>Condition is valid.</span> <ng-template #condition1>Condition is valid from template</ng-template> <ng-template #condition2>Condition is invalid from template</ng-template> </div> <button (click)=”myClickFunction($event)”>Click Me</button> If we remove the then condition, we get the “Condition is valid” message in the browser and the span tag is also available in the dom. For example, in app.component.ts, we have made the isavailable variable as true. Print Page Previous Next Advertisements ”;
Angular 4 – Directives
Angular 4 – Directives ”; Previous Next Directives in Angular is a js class, which is declared as @directive. We have 3 directives in Angular. The directives are listed below − Component Directives These form the main class having details of how the component should be processed, instantiated and used at runtime. Structural Directives A structure directive basically deals with manipulating the dom elements. Structural directives have a * sign before the directive. For example, *ngIf and *ngFor. Attribute Directives Attribute directives deal with changing the look and behavior of the dom element. You can create your own directives as shown below. How to Create Custom Directives? In this section, we will discuss about Custom Directives to be used in components. Custom directives are created by us and are not standard. Let us see how to create the custom directive. We will create the directive using the command line. The command to create the directive using the command line is − ng g directive nameofthedirective e.g ng g directive changeText This is how it appears in the command line C:projectA4Angular 4-app>ng g directive changeText installing directive create srcappchange-text.directive.spec.ts create srcappchange-text.directive.ts update srcappapp.module.ts The above files, i.e., change-text.directive.spec.ts and change-text.directive.ts get created and the app.module.ts file is updated. app.module.ts import { BrowserModule } from ”@angular/platform-browser”; import { NgModule } from ”@angular/core”; import { AppComponent } from ”./app.component”; import { NewCmpComponent } from ”./new-cmp/new-cmp.component”; import { ChangeTextDirective } from ”./change-text.directive”; @NgModule({ declarations: [ AppComponent, NewCmpComponent, ChangeTextDirective ], imports: [ BrowserModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } The ChangeTextDirective class is included in the declarations in the above file. The class is also imported from the file given below. change-text. directive import { Directive } from ”@angular/core”; @Directive({ selector: ”[changeText]” }) export class ChangeTextDirective { constructor() { } } The above file has a directive and it also has a selector property. Whatever we define in the selector, the same has to match in the view, where we assign the custom directive. In the app.component.html view, let us add the directive as follows − <div style=”text-align:center”> <span changeText >Welcome to {{title}}.</span> </div> We will write the changes in change-text.directive.ts file as follows − change-text.directive.ts import { Directive, ElementRef} from ”@angular/core”; @Directive({ selector: ”[changeText]” }) export class ChangeTextDirective { constructor(Element: ElementRef) { console.log(Element); Element.nativeElement.innerText=”Text is changed by changeText Directive. “; } } In the above file, there is a class called ChangeTextDirective and a constructor, which takes the element of type ElementRef, which is mandatory. The element has all the details to which the Change Text directive is applied. We have added the console.log element. The output of the same can be seen in the browser console. The text of the element is also changed as shown above. Now, the browser will show the following. Print Page Previous Next Advertisements ”;