Sepcio
Sepcio

Reputation: 255

Prevent data bind for child component in ngFor

I have a component that is using child component inside ngFor loop. This child component has a data binding that is read with @Input.

The problem I'm facing is that when I push data to Child Component, each instance of child component gets the same value. Is there any way to push data only for a specific instance of child component bind in ngFor?

Here is a dummy example I created

I want it to work in that way when I click the first button, only the first child component should get value but second, should be empty.

I'm new in angular environment so any help will be great.

Upvotes: 1

Views: 422

Answers (1)

Joe - Check out my books
Joe - Check out my books

Reputation: 16895

pushToChild would be shared across the children so let's not use it. The simplest way I can think of is passing the values directly to the children using a child DOM element converted to a variable declaration (#child) which is unique when looping thru.

.ts

import { Component } from '@angular/core';
import { ChildComponent } from './child-component/child.component';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  object: { [key: number]: string } = { 2: 'foo', 1: 'bar' };

  push(value: any, child: ChildComponent) {
    child.data = value;
  }
}

.html

<span>
  <p>Some dummy list</p>
  <div *ngFor="let item of object | keyvalue"
       style="background:gray; margin-top:0.5rem">
    Click button to push value: {{ item.key }} to child
    <button (click)="push(item.key, childRef)">Push</button>
    <child-component #childRef></child-component>
  </div>
</span>

Upvotes: 1

Related Questions