Reusable Component

Component API

If you want to make your component to be reusable, you should add input and output properties in your component. Just like the button element from HTML itself has “click” property, you can bind the click properties with some methods in your code to respond to users’ operations. In your component, you need to create those properties on your own.

Input Properties

For example, you have a new component called ‘favorite’.

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

@Component({
  selector: 'favorite',
  templateUrl: './favorite.component.html',
  styleUrls: ['./favorite.component.css']
})
export class FavoriteComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

First, you need to import ‘input’ from “angular core” ; after that, add ‘@input()’ in front of your field;

import { Component, OnInit, input } from '@angular/core';

@Component({
  selector: 'favorite',
  templateUrl: './favorite.component.html',
  styleUrls: ['./favorite.component.css']
})
export class FavoriteComponent implements OnInit {
  @input() isFavorite: boolean;

  constructor() { }

  ngOnInit() {
  }

}

Now, this field is exposed to outside as a property. You can use it like:

<favorite [isFavorite]='post.isFavorite'></favorite>

you can add a string as a parameter of input to give your property another name.

@input('is-favorite') isFavorite: boolean;

output property

For example, you want to add a property called ‘change’ to your favorite component; you want that when a user clicks on the icon, some events will be raised.

<favorite [isFavorite]='post.isFavorite' (change)='theIconHasChanged()'></favorite>

You need to define an output property in this situation

First, you import the Output from the core;

Create a field, the name should be the same as your property. Decorate it with the output decorator

import { Component, OnInit, Input, Output,EventEmitter } from '@angular/core';

@Component({
  selector: 'favorite',
  templateUrl: './favorite.component.html',
  styleUrls: ['./favorite.component.css']
})
export class FavoriteComponent implements OnInit {
  @input() isFavorite: boolean;
  @Output() change = new EventEmitter();

  constructor() { }

  ngOnInit() {
  }

  onClick(){
    this.change.emit();
  }

}

 

Leave a Reply

Your email address will not be published. Required fields are marked *