Carl Rippon

Building SPAs

Carl Rippon
BlogBooks / CoursesAbout
This site uses cookies. Click here to find out more

Building a simple component in Angular 2

January 22, 2016
angular

A while back, I posted about building a simple component in react. In this post, I’m going to go through building that same component in Angular 2 …

The component will look like below. There will be a parent component with 2 child components …

  • Criteria. The search textbox and “go” button
  • Results. The list of results
  • Search. The overall component – the parent of Criteria and Results

search results components

Consuming component

The code of the consuming component is listed below …

import { Component } from "angular2/core";
import { SearchComponent } from "./search.component";

@Component({
  selector: "my-app",
  directives: [SearchComponent],
  template: `
    <search></search>
  `
})
export class AppComponent {}
  • On line 2, we import the search component which is our top level component
  • On line 6, we declare that we are going to use the search component in the component’s markup
  • Finally on 8, we reference the search component, using it’s tag which will be search

Search component

The code for the search component is listed below …

import { Component } from "angular2/core";
import { Customer } from "./customer";
import { CriteriaComponent } from "./criteria.component";
import { ResultsComponent } from "./results.component";

@Component({
  selector: "search",
  directives: [CriteriaComponent, ResultsComponent],
  template: `
    <div>
      <criteria (update)="handleSearch($event)"></criteria>
      <results [data]="filteredCustomers"></results>
    </div>
  `
})
export class SearchComponent {
  customers: Customer[];
  filteredCustomers: Customer[];
  constructor() {
    this.customers = [
      { name: "Alfreds Futterkiste" },
      { name: "Berglunds snabbköp" },
      { name: "Cactus Comidas para llevar" },
      { name: "Chop-suey Chinese" },
      { name: "Du monde entier" },
      { name: "Ernst Handel" },
      { name: "France restauration" },
      { name: "Island Trading" },
      { name: "Let's Stop N Shop" },
      { name: "Maison Dewey" },
      { name: "Paris spécialités" },
      { name: "Que Delícia" },
      { name: "Rancho grande" }
    ];
    this.filteredCustomers = [];
  }
  private getCustomers(criteria: string): Customer[] {
    var ret: Customer[] = [];
    for (let i = 0; i < this.customers.length; i = i + 1) {
      if (this.customers[i].name.toLowerCase().indexOf(criteria) === 0) {
        ret.push(this.customers[i]);
      }
    }
    return ret;
  }
  private handleSearch(args): void {
    var i, ret;
    this.filteredCustomers = this.getCustomers(args.value);
  }
}
  • Lines 3 and 4 import the criteria and results components
  • Line 8 declares that the criteria and results components are going to be referenced in the markup
  • Line 11 references the criteria component and calls the handleSearch() function when the critieria’s update event occurs
  • handleSearch() is declared on lines 33 to 37. The implementation finds the customers matching the given criteria and sets the filteredCustomers property
  • Line 12 references the results component and sets its data property to the search component’s filteredCustomers property. The data property will be updated every time the filteredCustomers property is updated automatically by angular

Criteria component

The code for the criteria component is listed below …

import { Component, Output, EventEmitter } from "angular2/core";

@Component({
  selector: "criteria",
  template: `
    <div>
      <input #criteria type="search" placeholder="Search criteria" />
      <button (click)="handleClick(criteria.value)">Go</button>
    </div>
  `
})
export class CriteriaComponent {
  @Output() update: EventEmitter<any> = new EventEmitter();
  constructor() {}
  public handleClick(value: string): void {
    this.update.next({ value: value });
  }
}
  • There is an update custom event declared on line 14. The search component makes use of this to trigger a search
  • Line 8 calls the handleClick() method, passing the value of the criteria, which in turn triggers the update event

Results component

The code for the results component is listed below …

import { Component, Input } from "angular2/core";
import { Customer } from "./customer";

@Component({
  selector: "results",
  template: `
    <h2>Results</h2>
    <ul style="{listStyle}">
      <li *ngFor="#customer of data">
        {{ customer.name }}
      </li>
    </ul>
  `
})
export class ResultsComponent {
  @Input() data: Customer[];
  constructor() {}
}
  • On line 17 we have a custom property declared called data which the search component uses to pass in the data
  • Lines 9 to 11 make use of angular’s ngFor to iterate over the data and display the name for each item

That’s it - pretty simple!

Want more content like this?

Subscribe to receive notifications on new blog posts and courses

Required
© Carl Rippon
Privacy Policy