Enable and disable button of product list in angular 6

Posted at: October 5, 2018 11:38 AM

Example of Input and Output Property in Angular 6/7

Input and Output property in Angular 6 with example enable and disable button of product list


Parent Component ts File

product.component.ts

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

@Component({
  selector: 'app-product',
  templateUrl: './product.component.html',
  styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {

  title = 'Products';

  products = [
    { id: 1, name: 'Watch', price: '5000.00' },
    { id: 2, name: 'T-Shirt', price: '2000.00' },
    { id: 3, name: 'Bag', price: '1000.00' },
    { id: 4, name: 'Laptop', price: '40000.00' },
    { id: 5, name: 'LED TV', price: '25000.00' }
  ];

  productStatus: string;

  constructor() { }

  ngOnInit() {
  }

  onStatus(active: boolean) {
    active ? this.productStatus = 'Enabled' : this.productStatus = 'Disabled';
   }
}

Parent Component html File

product.component.html

<h2>{{title}}</h2>

<p>Product status <strong>{{productStatus}}</strong></p>

<app-product-list *ngFor="let product of products" [product]="product" (status)="onStatus($event)"></app-product-list>

Child Component .ts File

product-list.component.ts

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

@Component({
  selector: 'app-product-list',
  templateUrl: './product-list.component.html',
  styleUrls: ['./product-list.component.css']
})
export class ProductListComponent implements OnInit {

  @Input() product;
  @Output() status = new EventEmitter<boolean>();

  enabled: boolean;
  disabled: boolean;

  constructor() { }

  ngOnInit() {
  }

  isActive(active: boolean) {
    this.status.emit(active);
    if (active) {
      this.enabled = true;
      this.disabled = false;
    } else {
      this.enabled = false;
      this.disabled = true;
    }
  }

}

Child Component .html File

product-list.component.html

<p>
  {{product.id}}
  {{product.name}}
  {{product.price}}
  <button (click)="isActive(true)" [disabled]="enabled">Enabled</button>
  <button (click)="isActive(false)" [disabled]="disabled">Disabled</button>
</p>

Output

input-output-property
Input Property Output Property EventEmitter

Please leave comments

8 Comments