Angular 2 Directives-Components - Angular 2

What is the use of components in angular 2?

Description

Component is a controller class with a template which deals with application and logic a view in a page. It is a bit of code which can be used throughout an application. Component knows how to render itself and configure dependency injection.

Component contains 2 important things, view and some logic.

Example

Below example describes the use of component in Angular 2:

Above code includes below configuration options:

  • User can configure index.html file using typescript version. SystemJS transpilers TypeScript to JavaScript before running the application using the transpiler option.
  • If the user does not want to transpile to JavaScript before running the application, they can see the compiler warnings and errors hidden in the browser.
  • The TypeScript generates metadata for each and every class of the code when the emitDecoratorMetadata option is set. If you don't specify this option, large amount of unused metadata will be generated which affects the file size and impact on the application runtime.
  • Angular 2 includes packages form the app folder where files will have the .ts extension.
  • Next it loads the main component file from the app folder. If main component file is not found, then it will display the error in the console.
  • When Angular calls the bootstrap function in main.ts, it reads the Component metadata, finds the 'app' selector, locates an element tag named app, and loads the application between those tags.

To run the code, TypeScript(.ts) files are needed which should be saved under the app folder.

component_main.ts

Now create a component in TypeScript(.ts) file which creates a component and view for the component.

component_app.component.ts

Output

Running the above code, displays the text specified within the template option which is defined in the component_app.component.ts file and holds component's companion template that tells Angular how to render a view.

Below steps can be carried out to see how above code works:

  • Save above HTML code as index.html file as and use the above app folder which contains .ts files.
  • Open the terminal window and enter below command:

  • After few minutes, a browser tab should open and should display the output as shown below.

OR this file can be run in another way:

  • Save above HTML code as angular2_components.html file in the server root folder.
  • Open this HTML file as http://localhost/angular2_components.html and output as shown below will be displayed.

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Angular 2 Topics