Tuesday, April 17, 2018

Angular - Creating a Component in Angular


A Component has 3 parts

  • Template
    • View layout
    • Created with HTML
    • Includes binding and directives
  • Class
    • Code supporting the view
    • Created with TypeScript (.ts file)
    • Properties for data
    • Methods for logic
  • CSS
    • A CSS file for the styling needed for the component
  • Metadata
    • Extra data for Angular
    • Defined with a decorator


app.component.ts file

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

  selector: 'myApp-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
export class AppComponent {
  title = 'Hello World';

  • The import pulls in dependency references
  • @Component is the metadata / decorator that says the class is a component. This is similar to an [Attribute] in C#
  • export makes the class definition available for user elsewhere.
  • The selector is a unique value for this component in the application. It is suggested you prefix selectors with something that identifies it as part of your app. This is also what is used as a tag to use this component in another component. In this case it is <myApp-root><myApp-root>
  • It is common to append "Component" to the name name of the class so that it is clear that it is a component.



This is the HTML that defines the layout. Anything in {{...}} tags are binds to properties in the class associated with this component.


h1 { text-align:center }

This is a standard CSS file, except these styles will be unique to this component automatically. They will not affect other styles in the project.


Some common Angular Modules you may need to import are:
  • @angular/core (as we have done above)
  • @angular/animate
  • @angular/http
  • @angular/router

Using the Component

This is how you would use it in index.html for example:


Telling index.html about our Component

In app.module.ts you list what angular modules should be included in our application#

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';

  declarations: [ AppComponent ],
  imports: [ BrowserModule ],
  providers: [],
  bootstrap: [AppComponent]
export class AppModule { }

No comments: