• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

Angular 5 Component Example (Formerly Angular 2)

May 8, 2018 by javainterviewpoint Leave a Comment

In this article, we will get to know about Angular 5 Component. Angular Component are the basic building block of an angular application, which allows you to control how your application looks and functions. There are three steps involved to create a component.

  1. Importing Component Decorator dependencies
  2. Adding Metadata in the Component decorator
  3. Exporting the Class

Angular 5 Component Example

Before getting into the details, lets first create a hello component, which we will be able to use in our HTML using <app-hello> </app-hello> tag.

In order to create a new component using Angular CLI, we can use the generate command.

ng generate component hello

C:\Angular5\myapp> ng generate component hello
  create src/app/hello/hello.component.html (24 bytes)
  create src/app/hello/hello.component.spec.ts (621 bytes)
  create src/app/hello/hello.component.ts (265 bytes)
  create src/app/hello/hello.component.css (0 bytes)
  update src/app/app.module.ts (824 bytes)

Project Structure

├── e2e
├── node_modules
├── src
│   ├── app
│   │   │── hello
│   │   │   │── hello.component.html
│   │   │   │── hello.component.spec.ts
│   │   │   │── hello.component.ts
│   │   │   │── hello.component.css
│   │   │── app.component.css
│   │   │── app.component.html
│   │   │── app.component.spec.ts
│   │   │── app.component.ts
│   │   │── app.module.ts
│   ├── assets
│   │   │── .gitkeep
│   ├── environments
│   │   │── environment.prod.ts
│   │   │── environment.ts
│   ├── favicon.ico
│   ├── index.html
│   ├── main.ts
│   ├── polyfills.ts
│   ├── styles.css
│   ├── test.ts
│   ├── tsconfig.app.json
│   ├── tsconfig.spec.json
│   ├── typings.d.ts

The above command will create hello.component.ts component with the below code

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

@Component({
  selector: 'app-hello',
  templateUrl: './hello.component.html',
  styleUrls: ['./hello.component.css']
})
export class HelloComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

1. Importing Component Decorator dependencies

  • In our first statement, we are importing the dependencies which we want to use in our Component, in our case it is Component and onInit.
  • We are importing both Component and onInit from ‘@angular/core’ module. The ‘@angular/core’ module points the compiler to define and export those two dependencies.

2. Adding Metadata in the Component Decorators

After importing the required dependencies we will be decorating the class with @Component decorator. It provides the metadata information about our code. @Component decorator has a several configuration option, below are some of the most used options.

  • selector: This option defines the name of HTML tag which will be used in our DOM (HTML)
  • template: This option lets you add inline HTML
  • templateUrl: This option lets you import an external template file rather than inline HTML template.
  • styles: This option allows you to add inline CSS to your component.
  • stylesUrls: This option allows you to import an external CSS stylesheet.

selector

Selector is the HTML tag which we will be using in our DOM, in our application the selector is <app-hello></app-hello>. There are three different types of selectors which we can use

  • Element Selector:

This selector looks similar to CSS selector, we can use <app-hello></app-hello> tags in our HTML to use this selector

@Component({
  selector: 'app-hello',
  templateUrl: './hello.component.html',
  styleUrls: ['./hello.component.css']
})
  • Attribute Selector:

Enclose our selector within the Square brackets [] to make it an Attribute selector.

@Component({
  selector: '[app-hello]',
  templateUrl: './hello.component.html',
  styleUrls: ['./hello.component.css']
})

Now we cannot use <app-hello></app-hello> tags. In order to use Attribute selector, we need to create an HTML element may be a <div> tag and add app-hello as an attribute like below

<div app-hello></div>

Note: Attribute selector cannot be used directly like the Element Selector it has to be embedded within the HTML tag as an attribute

  • Class Selector:

Add Dot ‘.’ in front of our selector like a CSS Class to make it a Class selector.

@Component({
  selector: '.app-hello',
  templateUrl: './hello.component.html',
  styleUrls: ['./hello.component.css']
})

In order to use Class selector create an HTML element may be a <div> tag and add app-hello as CSS class like below

<div class=”app-hello”></div>

templateUrl

template defines the Layout of the View which will be rendered to the user. Without the template, Angular will have nothing to be rendered. In the above component which we have created we have used the templateUrl as ‘./hello.component.html’, This means angular will load the template from the hello.component.html located in the same directory.

<h3>Angular 5 Component Example</h3>

template

Using the template option, we can define the HTML markup inline, in order to define multiline strings in the template we need to use backticks ``

@Component({
  selector: '.app-hello',
  template: `<h3>Angular 5 Component Example</h3>`,
  styleUrls: ['./hello.component.css']
})

stylesUrls

stylesUrls informs Angular that we want to use CSS specified in the external file, in our application we are using hello.component.css as the styles for this component. Angular uses a concept called “style-encapsulation” which means that styles specified for a particular component will be only applied to that component alone.

@Component({
  selector: '.app-hello',
  templateUrl: './hello.component.html',
  styleUrls: ['./hello.component.css']
})

styles

Using the styles option, we can define the CSS Styles inline.

@Component({
    selector: 'app-hello',
    templateUrl: './helloworld.component.html',
    styles: [ `
            h3 {
                font-size:36px;
            }`]
})

3. Exporting the Class

A class is a new feature of ES6, it’s a blueprint for creating objects with specific functions and properties attached to it. We have used the export statement, so that this component can be imported into a different angular components.

export class HelloComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

With classes we can initialize properties when we instantiate an object using a special function called as constructor. Lets take a look in below code.

export class HelloComponent implements OnInit {
  welcomeMessage: String;
  constructor() {
    this.welcomeMessage = "Welcome to Angular Component Example";
  }

  ngOnInit() {}
}

In the above code, the welcomeMessage string will be initialized the moment we instantiate our HelloComponent class.

Happy Learning!! 🙂

Angular 5 Component

Filed Under: Angular, J2EE Tagged With: Angular 5, Angular 5 Component, Angular 5 Components, Angular Component, Angular Components, Component

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·