Search code examples
angularangular2-routingangular8

angular 8 how to use component multiple times in parent component with different action


I have a component that can be used multiple times in parent component with diffrent action. How would i get my component clicked event to parent.

My Component that can be used multiple times:

    import {Component} from 'angular2/core';

    @Component({
        selector: 'my-card',
        template: `<button (click)="onClickMe()">select</button>`
    })
    export class MyCardComponent {
    onClickMe() {
       //if my-card in parent component is type 1 do some thing
       //if my-card in parent component is type 2 do some thing
    }
   }

my parent component html :

<div>
   <p>Type 1<p>
  <my-card></my-card>
</div>

<div>
    <p>Type 2<p>
  <my-card></my-card>
</div>

how can i do it?


Solution

  • With @Output

    @Output() someClickAction = new EventEmitter<void>();

    You can also send some data just change the void to the right data type.

    Then in onClickMe() just call emit on the someClickAction property.

    import {Component, EventEmitter, Output} from '@angular/core';
    
    @Component({
      selector: 'my-card',
      template: `<button (click)="onClickMe()">select</button>`
    })
    export class MyCardComponent {
      @Output() someClickAction = new EventEmitter<void>();
    
      onClickMe() {
        this.someClickAction.emit();
    
      }
    }
    

    In html it would look like this.

    <div>
      <p>Type 1</p>
      <my-card (someClickAction)="someFunction()"></my-card>
    </div>
    
    <div>
      <p>Type 2</p>
      <my-card (someClickAction)="someOtherFunction()"></my-card>
    </div>
    

    With @Input()

    Here you wouldn't send info about click to child but you will specify type in parent and child will behave based on the value.

    By @Input you specify you attribute for your component

    import {Component, EventEmitter, Input} from '@angular/core';
    
    @Component({
      selector: 'my-card',
      template: `<button (click)="onClickMe()">select</button>`
    })
    export class MyCardComponent {
      @Input() type: number;
    
      onClickMe() {
        if(this.type === 1) {
    
        } else if(this.type === 2) {
    
        }
      }
    }
    

    In HTML

    <div>
      <p>Type 1</p>
      <my-card [type]="1"></my-card>
    </div>
    
    <div>
      <p>Type 2</p>
      <my-card [type]="2"></my-card>
    </div>
    

    You can read more about it here