Passionate Coder
Passionate Coder

Reputation: 7294

Not able to understand Input decorator behaviour

I am implementing Input and Output decorator and I got confused about a functionality. What is happening here?

Parent Component

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './template.html'
})
export class ParentComponent {

}

parent template

<h1>Parent</h1>
<app-child placeHolderTxt="Add User"></app-child>
<app-child placeHolderTxt="Add Admin"></app-child>

Child Component

import { Component, Input } from '@angular/core';
@Component({
  selector: 'app-child',
  templateUrl: './template.html'
})
export class ChildComponent {

  @Input() placeHolderTxt = "";
  count = 0;  
  addUser = function(){
    this.count += 1;    
  }
}

child template

<div style="float:left;margin-left:100px; border: 1px solid black">
    <table>
        <tr>
            <td><input type="text" placeholder="{{placeHolderTxt}}"/></td>
            <td><input type="button" (click)="addUser()" value="ADD"/></td>
        </tr>
        <tr>
            <td>Total Count : {{count}}</td>            
        </tr>
    </table>
</div>

enter image description here

When I am clicking in Add User Add button it increases count by 1 each time but the count for admin remains 0. My problem is that I am not able to understand why it's showing 0 count for admin as for display count. I am using same child component member.

Upvotes: 0

Views: 41

Answers (1)

LppEdd
LppEdd

Reputation: 21114

The count field isn't shared between Component instances.

You have two app-child elements, and it means you'll have two independent counts.

<app-child placeHolderTxt="Add User" [count]="count" (increment)="onIncrement()"></app-child>
<app-child placeHolderTxt="Add Admin" [count]="count" (increment)="onIncrement()"></app-child>

You can leverage an @Output EventEmitter, and move up the count variable.

export class ChildComponent {
  @Input() placeHolderTxt = "";
  @Input() count = 0;

  @Output() increment = new EventEmitter<void>(true);

  addUser(): void {
    this.increment.emit();
  }
}

export class ParentComponent {
  count = 0;

  onIncrement(): void {
    this.count++;
  }
}

Upvotes: 2

Related Questions