Angular: angular component

What is an Angular Component

  • The Component is the main building block of an Angular Application.
  • The component contains the data & user interaction logic that defines how the View looks and behaves.
  • A view in Angular refers to a template (HTML).
  • The Angular Components are plain JavaScript classes and defined using @Component Decorator.
  • This Decorator provides the component with the View to display & Metadata about the class
  • The Component is responsible to provide the data to the view. The Angular does this by using data binding to get the data from the Component to the View.
  • This is done using the special HTML markup knows as the Angular Template Syntax. The Component can also get notified when the View Changes.
  • The Angular applications will have lots of components. Each component handles a small part of UI.
  • These components work together to produce the complete user interface of the application
  • The Components consist of three main building blocks
    • Template
    • Class
    • MetaData

Building blocks of the Angular Component

Template (View)

  • The template defines the layout of the View and defines what is rendered on the page. Without the template, there is nothing for Angular to render to the DOM.
  • The Templates are created with HTML.
  • You can add Angular directives and bindings on the template.
  • There are two ways you can specify the Template in Angular.
    • Defining the Template Inline
    • Provide an external Template

Class

  • The class is the code associated with Template (View).
  • The Class is created with Typescript, but you can also use JavaScript directly in the class.
  • Class Contains the Properties & Methods.
  • The Properties of a class can be bind to the view using Data Binding.
  • The simple Angular Class
  • export class AppComponent {
      title: string = 'app';
    }
  • The Component classes in Angular are prefixed with the name “Component”, To easily identify them.

Metadata

  • Metadata Provides additional information about the component to the Angular.
  • Angular uses this information to process the class. The Metadata is defined with a decorator.
  • A decorator is a function that adds metadata to class, its methods & to its properties.
  • The Components are defined with a @component class decorator. It is @component decorator, which defines the class as Component to the Angular

@Component decorator

  • A class becomes a Component when Component Decorator is used.
  • A Decorator is always prefixed with @.
  • The Decorator must be positioned immediately before the class definition. We can also build our own decorators.
  • The decorators are Similar to attributes in C#.

Important Component metadata properties

Selector

  • Selector specifies the simple CSS selector, where our view representing the component is placed by the Angular.

Providers

  • The Providers are the services, that our component going to use.
  • The Services provide service to the Components or to the other Services.

Directives

  • The directives that this component going to use are listed here: Directives

Styles/styleUrls

  • The CSS Styles or style sheets, that this component needs.
  • Here we can use either external stylesheet (using styleUrls) or inline styles (using Styles).
  • The styles used here are specific to the component

template/templateUrl

  • The HTML template that defines our View. It tells Angular how to render the Component’s view.
  • The templates can be:
    • inline (using a template)
    • or we can use an external template (using a templateUrl).
  • The Component can have only one template. You can either use inline template or external template and not both

Creating the Component

  • The Angular CLI has automatically created the root component app.component.ts.
  • Creation of the Angular component requires you to follow these steps:
    1. Create the Component file
    2. Import the required external Classes/Functions
    3. Create the Component class and export it
    4. Add @Component decorator
    5. Add metadata to @Component decorator
    6. Create the Template
    7. Create the CSS Styles
    8. Register the Component in Angular Module

1. Creating the Component File

  • The Component app.component.ts. is already been created for us by Angular CLI under the folder src.
  • By Convention, the file name starts with the feature name (app) and then followed by the type of class (component). These are separated by a dot.
  • The extension used is ts indicating that this is a typescript module file.
  • Create a component using angular cli:
    • Open project in vs code
      • Browse in project folder CMD
      • Type "code ." then enter
    • Add component
      • Use angular cli
      • ng g c [ComponentName]

2. Import the Angular Component Object

  • The Import statement is similar to the using statement in c#, which allows us to use the external modules in our class
  • To define the Component class, we need to use the @Component decorator. This function is found in the Angular core library.

3. Create the Component Class and export it

  • The Export keyword allows this component class to be used in other components by importing. The AppComponent class is shown below
  • export class AppComponent {
      title = 'app';
    }

4. Add @Component decorator

  • The next step is to inform the Angular that this is a Component class.
  • This is done by adding the @Component decorator to the above class.
  • The decorator must be added immediately above the class as shown below
  • @Component({
    })
    export class AppComponent {
      title = 'app';
    }

5. Add metadata to @Component decorator

  • The next step is to add the metadata to the @component decorator.
  • Add the following to the component metadata
  • @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
  • Selector
    • The angular places the view (template) inside the selector app-root
  • templateUrl
    • In the above example, we have used an external template using templateUrl metadata.
    • The templateUrl points to the external HTML file app.component.html.
  • styleUrls
    • Defines the styles for our template.
    • The metadata points to the external CSS file app.component.css.
    • The Component specific CSS styles can be specified here.

6. Create the Template (View)

  • Template is nothing but an HTML file, which component must display it to the user
  • The Angular knows which template display, using the templateUrl metadata, which points to app.component.html.
  • <!-- The content below is only a placeholder and can be replaced. -->
    <div style="text-align:center">
      <h1>
        Welcome to {{title}}!
      </h1>
      <img width="300" src="/images/branding/googlelogo/2x/googlelogo_light_color_92x30dp.png">
    </div>
    <h2>Here are some links to help you start: </h2>
    <ul>
      <li>
        <h2><a target="_blank" href="https://angular.io/tutorial">Tour of Heroes</a></h2>
      </li>
      <li>
        <h2><a target="_blank" href="https://github.com/angular/angular-cli/wiki">CLI Documentation</a></h2>
      </li>
      <li>
        <h2><a target="_blank" href="https://blog.angular.io//">Angular blog</a></h2>
      </li>
    </ul>
  • By Convention, the file is named after the component file it is bound to with HTML extension.
  • This is a simple HTML file, except for the initial h1 tag
  • <h1>
      Welcome to {{title}}!
    </h1>
  • Note that title inside the double curly bracket. When rendering the view, the Angular looks for title Property in our component and binds the property to our view. This is called data binding.
  • The double curly bracket syntax is known as interpolation

7. Add the Styles

  • The next step is to add the CSS Styles.
  • The styleUrls metadata tells Angular, where to find the CSS File. This property points to external file app.component.css
  • By Convention, the file is named after the component file it is bound to with .css extension
  • Note that styleUrls metadata can accept multiple CSS Files.

8. Register the Angular Component in Angular Module

  • The Angular Module organizes the components, directives, pipes, and services that are related and arranges them into cohesive blocks of functionality.
  • It is a class that is adorned with @NgModule decorator
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 { }
    
  • We use @NgModule class decorator to define a Module and provide metadata about the Modules.
  • We add all the components, pipes and directives that are part of this module to the declarations array.
  • We add all the other modules that are used by this module to imports array.
  • We include the services in the providers’ array.
  • The Component that Angular should load when the app.module is loaded is assigned to the bootstrap property.
import { AppComponent } from './app.component';

    @NgModule({
      declarations: [AppComponent],
      // Other module properties go here
    })
    
  • We want appComponent to be loaded when Angular starts, thus we assign it to bootstrap property
bootstrap: [AppComponent]
    
  • Finally, run the application from the command line using ng serve ( or npm start). You should see this

Creating the Inline Template & StyleUrls

  • In the above example, we have used the external template & Styles.
  • We can also specify the Template, Styles inline using the template and styles property of @Component metadata as shown below.
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: '{{title}} works',
  styles: ['h1 { font-weight: bold; }']
})
export class AppComponent {
  title = 'app';
}
  • The Template can get pretty long. In the case of a Multi-line template, you can use BackTicks ( ` ) to enclose the template string.
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    {{title}} works
    

a long inline template

`, styles: ['h1 { font-weight: bold; }'] }) export class AppComponent { title = 'app'; }

The component selector

  • The Angular renders the components view in the DOM inside the CSS selector, that we defined in the Component decorator
@Component({
  selector: 'app-root',
  // Other properties go here
})
  • The selector <app-root></app-root> is in the index.html (under src folder)
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Angular4</title>
    <base href="/">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/x-icon" href="favicon.ico">
  </head>
  <body>
    <app-root></app-root>
  </body>
</html>
  • When we build Angular Components, we are actually building new HTML elements. We specify the name of the HTML element in the selector property of the component metadata. And then we use it in our HTML.
  • The Angular, when instantiating the component, searches for the selector in the HTML file and renders the Template associated with the component.
  • That gives several options to use our component selector

Using the CSS class name

@Component({
  selector: '.app-root',
  // Other properties go here
})

And in the HTML markup use the CSS class name

<div class="app-root"></div>

Using attribute name

@Component({
  selector: '[app-root]',
  // Other properties go here
})

And you can now use the attribute as follows

<div app-root></div>

Using attribute name and value

@Component({
  selector: 'div[app=components]',
  // Other properties go here
})

Now you can use it as follows

<div app="components"></div>

Comments

Popular posts from this blog

C# Windows Form : PetCare

Fake Call Android Application

Car Wash System vb.net