Skip to content

Components

Aakash Goplani edited this page Jul 3, 2020 · 15 revisions

What are Components

  • Components are the most basic building block of an UI in an Angular application. An Angular application is a tree of Angular components. Components always have a template and only one component can be instantiated per an element in a template. It has three main properties / meta-data:

    1. selector: A CSS selector that tells Angular to create and insert an instance of this component wherever it finds the corresponding tag in template HTML. For example, if an app's HTML contains <app-hero-list></app-hero-list>, then Angular inserts an instance of the HeroListComponent view between those tags. It should always be unique.

    2. templateUrl: The module-relative address of this component's HTML template. Alternatively, you can provide the HTML template inline, as the value of the template property. This template defines the component's host view.

      • You can also use template property to define HTML inline. e.g. template: '<p>Hello</p>'
    3. styleUrls[]: All styles related to the component template should be defined inside the file specified in the component decorator.

      • You can also use styles[] property to define CSS inline. e.g. styles: ['p { color: red; }']
  • The @Component decorator identifies the class immediately below it as a component class, and specifies its metadata.

  • The metadata for a component tells Angular where to get the major building blocks that it needs to create and present the component and its view. In particular, it associates a template with the component, either directly with inline code, or by reference. Together, the component and its template describe a view.

  • In addition to containing or pointing to the template, the @Component metadata configures, for example, how the component can be referenced in HTML and what services it requires.

  • A Component simply is just a class, a TypeScript class, so that Angular is able to instantiate. So always export this class so that it can be used outside of the file too.

  • It to create objects based on the blueprint we set up here you could say.

Some conventions while creating Components

  1. Components for individual entity or use-case should be created inside a new sub-folder under app/ folder.
  2. Folder name should be same as component name and each component should have its own folder.
  3. Naming convention: <name_of_component>.component.ts

Ways to create selector

  1. Normal Way (recommended)
    selector: 'app-root' => <app-root></app-root>

  2. Selector as Attribute
    selector: '[app-root]' => <div app-root></div>

  3. Selector as Class
    selector: '.app-root' => <div class="app-root"></div>
    You CANNOT associate it with id

Notes

  • If templateUrl and template both are mentioned as meta-data of component, templateUrl gets the preference
  • To write multi-line HTML/CSS inine use back-ticks e.g.
    • Single line 'hello'
    • Multi line HTML: <abc>.......</abc>
    • Multi line CSS: [p{}, a{},... ] (use back-ticks, edit & look)
  • If styleUrls[] and styles[] both are mentioned as meta-data of component, styleUrls[] gets the preference

What are Decorators

  • Decorators, also called annotations, is a function that modifies a class or property definition. Angular defines decorators that attach metadata to classes or properties so that it knows what those classes or properties mean and how they should work.

  • Decorators are always attached by adding an @ sign in front of them.


What are Modules

  • In Angular, a module is a mechanism to group components, directives, pipes and services that are related, in such a way that can be combined with other modules to create an application. An Angular application can be thought of as a puzzle where each piece (or each module) is needed to be able to see the full picture.

Component Communication

Using @Input() and @Output() selector

  1. @Input()

    • If you want to pass data from the parent component to the child component, then you need to use two things: @Input and property binding.
    • In this example, we set in the child component an variable named childExample which is a string. In front of the variable we set Angular's: @Input decorator.
    import { Component, OnInit, Input } from '@angular/core';
    @Component({
      selector: 'app-child',
      template: '{{childExample}}'
    })
    export class ChildComponent implements OnInit {
      @Input() childExample: string = '';
    }
    • This gives the option to add an attribute to the selector (<app-child>)of the child, highlighted in the example below;
    import { Component, OnInit} from '@angular/core';
    @Component({
      selector: 'app-parent',
      template: '<app-child [childExample]="parentExample"></app-child>'
    })
    export class ParentComponent implements OnInit {
      parentExample: string = 'Hello Angular 8';
    }
    • In the parent, we declare a variable named: parentExample. We gave it a value to [childExample]. The result is that you display the text Hello Angular 8 in the child component.
    • You can also use alias property of Input decorator, e.g.
    @Input(`childComponent`) childExample: string = '';

    and make following changes in parent component

    <app-child [childComponent]="parentExample"></app-child>
    • You can call Child component using newly assigned name 'childComponent'. Now the initial property name 'childExample' is suppressed and is no longer accessible, Calling child component now with 'childExample' will result in error
  2. @Outut() & EventEmitter

    • With @Output and EventEmitter, you can pass data back from the child to the parent component.
    • In the child, we declare a variable with the @Output decorator and a new EventEmitter and then we emit an event to the parent component by emit(). What we are doing here is that on every button click in the child component we are passing the exampleOutput to a parent component and storing those values in an array.
    import { Component, OnInit, EventEmitter, Output } from '@angular/core';
    ...
    template: '<!--collect name, type, content from input type field-->
            <button (click)="exampleOutput ">Example Output from Child</button>'
    ...
    @Output() exampleOutput = new EventEmitter<{type: string, name: string, content: string}>();
    exampleMethod() {
       this.exampleOutput.emit({type: this.type, name: this.name, content: this.content});
    }
    • In our parent component we can now set an event to the child selector (<app-child>). We use the exampleOutput from the child, which has as value a method called exampleMethodParent with parameter $event
    @Component({
      selector: 'app-parent',
      template: '<app-child *ngFor="let element of someArray" (exampleOutput)="exampleMethodParent($event)"></app-child>'
    })
    export class ParentComponent implements OnInit {
      import { Component, OnInit } from '@angular/core';
      someArray: = [];
      exampleMethodParent(contentDataFromEvent: {type: string, name: string, content: string}) {
        this.someArray.push({type: contentDataFromEvent.type, serverName: contentDataFromEvent.name, serverContent: ontentDataFromEvent.content});
    }
    • You can also use alias property of Output decorator, e.g.
    @Output(`childComponent`) exampleOutput : {} = {};

    and make following changes in parent component

    <app-child *ngFor="let element of someArray" (childComponent)="exampleMethodParent($event)"></app-child>
    • You can call Child component using newly assigned name 'childComponent'. Now the initial property name 'exampleOutput' is suppressed and is no longer accessible, Calling child component now with 'exampleOutput' will result in error
Clone this wiki locally