Code News

How Engineering Earth’s Climate Could Seriously Imperil Life

The Tortured Deep-Focus Faces of Tournament Chess Players

Ralph Lauren's Olympic Jacket Uses Heat-Conducting Ink

Beginner's Guide to Angular 4: Components

  • Angular is a popular framework for creating front ends for web and mobile applications. It all started with AngularJS 1.x and then AngularJS 2, and now it's finally Angular, with the latest updates and bug fixes being worked on by the Angular team.

    Components are an important part of an Angular web application. In this tutorial, you'll see how to get started with creating a web application using Angular, and you'll also get to know components.

    Getting Started

    Get started by installing Angular CLI using the node package manager (npm).

    npm install -g @angular/cli

    Once you have the Angular CLI installed, create a new Angular app using the CLI.

    ng new angular-app

    Navigate to the application folder and start the server.

    cd angular-app ng serve

    Point your browser to http://localhost:4200/ and you should have the default app running.

    Angular App Structure

    Navigate to the angular-app project folder and have a look at the project structure. Here is how it looks:

    Every Angular app has a root module where you define the main component to load. In the default Angular app, the root module is defined inside the app.module.ts. When the AppModule loads, it checks which component is bootstrapped and loads that module. As seen in the app.module.ts, the module which is bootstrapped is AppComponent. The AppComponent component is defined in the file app.component.ts.

    A component is defined using the @Component decorator. Inside the @Component decorator, you can define the component selector, the component template, and the related style. 

    What Is an Angular Component?

    Components are like the basic building block in an Angular application. Components are defined using the @component decorator. A component has a selector, template, style and other properties, using which it specifies the metadata required to process the component.

    From the official docs:

    Components are the most basic building block of an UI in an Angular application. An Angular application is a tree of Angular components. Angular components are a subset of directives. Unlike directives, components always have a template and only one component can be instantiated per an element in a template.

    The best way to understand something related to programming is by actually doing. So let's start by creating an Angular component for adding two numbers. Let's call it CalculatorComponent.

    Creating the Calculator Component

    Let's start by creating a component for our calculator. Inside the src/app folder, create a folder called calc. This is where our calc component will reside. Inside the calc folder, create a file called calc.component.html. This will be the template for our calculator component. Here is how it looks:

    <h1> Calculator component </h1>

    Create a file called calc.component.ts. This is where you'll define the calc component and specify the related metadata. You'll be defining the component using the @component decorator. To define the component, you need to import the component module from angular core.

    import { Component } from '@angular/core';

    Define the component by specifying the template, style, and selector. You'll also define a class to manage the template specified by the @component decorator. Here is how it looks:

    import { Component } from '@angular/core'; @Component({ selector: 'calc', templateUrl: 'calc.component.html', styleUrls: ['calc.component.css'] }) export class CalcComponent { }

    All styles related to the component template should be defined inside the file specified in the component decorator. So create a file called calc.component.css inside the calc folder. You'll put the style for the calculator component inside this file.

    Now that you have your component ready, let's define the component inside the root module app.module.ts. 

    First import the component inside the app.module.ts file and then include it in the declarations section. Here is how it looks after adding the CalcComponent:

    import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { CalcComponent } from './calc/calc.component' @NgModule({ declarations: [ AppComponent, CalcComponent ], imports: [ BrowserModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }

    As you can see in the root module app.module.ts, the AppComponent is the bootstrapped module and hence it will render by default. So, to view our calculator component, define it inside the app.component.html. Here is how the app.component.html file looks:

    <div style="text-align:center"> <calc></calc> </div>

    Save the above changes and start the server. You should be able to see the HTML content of the calculator component displayed.

    Adding the Calculator Functionality

    Let's start by adding a template for our Angular calculator. Add the following code to the calc.component.html file:

    <div class="container"> <div class="header"> <h2> Calculator component </h2> </div> <div class="grid"> <div class="row"> <div class="col-6"> <div class="operation"> <div class="row"> <div class="col-12"> <input type="number" name="" placeholder="number"> </div> </div> <div class="row"> <div class="col-12"> <input type="number" name="" placeholder="number"> </div> </div> <div> <div class="col-12"> <button class="button"> Add </button> </div> </div> </div> </div> <div class="col-6"> <div class="result"> <span> Result </span> </div> </div> </div> </div> </div>

    Add the following style to the calc.component.css file.

    .grid{ width: 100% } .row{ width: 100%; display: flex; } .col-1 { width: 8.33%; } .col-2 { width: 16.66%; } .col-3 { width: 25%; } .col-4 { width: 33.33%; } .col-5 { width: 41.66%; } .col-6 { width: 50%; } .col-7 { width: 58.33%; } .col-8 { width: 66.66%; } .col-9 { width: 75%; } .col-10 { width: 83.33%; } .col-11 { width: 91.66%; } .col-12 { width: 100%; } .header{ width: 100%; background-color: #003A60; height: 100px; } .header h2{ line-height: 100px; color: #fff; } .button { background-color: #4CAF50; /* Green */ border: none; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; } input{ border: none; border-bottom: 1px solid grey; width: 80%; margin: 0% 10%; padding: 5%; } .result{ background-color: #ddffff; width: 80%; margin: 20px 10px 10px 10px; height: 100px; border-left: 3px solid #2196F3; } .result span{ line-height: 100px; }

    Save the above changes and you should be able to view the following user interface.

    Let's add the ngModel directive to the above displayed input text boxes. Modify the calc.component.html code as shown below:

    <div class="row"> <div class="col-12"> <input [(ngModel)]="number1" type="number" name="" placeholder="number"> </div> </div> <div class="row"> <div class="col-12"> <input [(ngModel)]="number2" type="number" name="" placeholder="number"> </div> </div>

    As seen above, you have set the ngModel for the input text boxes to the variables number1 and number2. 

    Let's define the variables inside the CalcComponent in the calc.component.ts file.

    export class CalcComponent { public number1 : number; public number2 : number; }

    Now, when the user types into the text boxes, the corresponding ngModel variable gets updated. You can check by displaying the variable in the component's template file.

    <div class="result"> <span> Number 1 : {{number1}} Number 2 : {{number2}} </span> </div>

    Save the changes and enter values inside the input boxes, and you should have the data updated inside the span.

    Let's add a button click to the Add button which will calculate the sum of the number1 and number2 when clicked on the button.

    Modify the HTML code as shown to include the click directive.

    <button (click)="add()" class="button"> Add </button>

    Define the add function inside the CalcComponent as shown:

    import { Component } from '@angular/core'; @Component({ selector: 'calc', templateUrl: 'calc.component.html', styleUrls: ['calc.component.css'] }) export class CalcComponent { public number1 : number; public number2 : number; public result : number; public add(){ this.result = this.number1 + this.number2 } }

    As seen in the above code, the result of the addition is being placed in a variable called result.

    Let's modify the HTML template to display the result once the variable is set.

    <div class="result"> <span> Result : {{result}} </span> </div>

    Save the above changes and try to add two numbers by clicking on the Add button. You will have the result displayed in the user interface.

    Wrapping It Up

    In this tutorial, you saw how to get started with creating a web app using Angular 4. You learnt about Angular components and how to create one. You created a simple Angular component to add two numbers.

    Source code from this tutorial is available on GitHub. If you’re looking for additional resources to study or to use in your work, check out what we have available on Envato Market.

    Do let us know your thoughts, suggestions or any corrections in the comments below.

    22 hours 28 min ago

The Second Coming of Ultrasound

Pixek App Encrypts Your Photos From Camera to Cloud

What Has Tech Done to Fix Its Harassment Problem?

Newly Updated Course: Build a CMS With Laravel

  • What You'll Be Creating

    Want to build your own content management system (CMS) in 2018? Learn exactly how it's done in our comprehensive course Build a CMS With Laravel, freshly updated with brand new lessons to take advantage of the latest features of Laravel 5.

    What You’ll Learn

    Laravel is a PHP framework for modern web apps. Now on version 5, it’s a mature system that continues to win support due to its elegance and stability. Laravel ships with built-in support for database migrations, object-relational mapping, routing, and authentication, making it easier for developers to start and maintain their work.

    In this course, Envato Tuts+ instructor Jeremy McPeak will show you how to build a complete content management system (CMS) with the Laravel PHP framework. 

    You’ll learn some of the tasks and problems that are common to so many web development projects, and you’ll explore different possible solutions to them. You’ll be starting your CMS from scratch—complete with page, user, and blog management capabilities. This is a great way to expand your knowledge of the Laravel framework!

    Watch the Introduction Take the Course

    You can take our new course straight away with a subscription to Envato Elements. For a single low monthly fee, you get access not only to this course, but also to our growing library of over 1,000 video courses and industry-leading eBooks on Envato Tuts+. 

    Plus you now get unlimited downloads from the huge Envato Elements library of 420,000+ creative assets. Create with unique fonts, photos, graphics and templates, and deliver better projects faster.

    1 day 1 hour ago

President Trump's Fake News Awards Top This Week's Internet News Roundup

Want to Avoid Malware on Your Android Phone? Try the F-Droid App Store

Pages