Exsite
Exsite

Reputation: 177

Angular: pass dynamic values to nested components inside ngFor

I have a child component inside a ngFor loop to which i want to send dynamic values. This is what i have tried so far, but it does not seem to work

<div *ngFor="let item of clientOtherDetails">

<h1>{{item.name}}<h1>

<app-child-component [firstname]="item.firstname" [secondname]="item.secondname"><app-child-component>

</div>

and in the child component i am using @Input() to get the values

@Input() firstname;
@Input() secondname;

I am not getting the dynamic first name and last name

Any advice will be of great help. thanks in advance

Upvotes: 0

Views: 1000

Answers (1)

Srijon Chakraborty
Srijon Chakraborty

Reputation: 2164

I think I have a solution for you. Please check my code and stackblitz link=>
Child TS:

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

@Component({
  selector: 'app-child',
  template: `
    First:  <input type="textbox" [(ngModel)]='firstname'><br>
    Second: <input type="textbox" [(ngModel)]='secondname'> 
  `
})
export class AppChildComponent {
  //getting value from parent to child
  @Input() firstname: string;
  @Input() secondname: string;
}

Parent HTML:

<div *ngFor="let site of sites">
  <app-child [firstname]="site.name" [secondname]="site.sname"></app-child>
</div>

Parent TS:

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  sites=[{name:'aa',sname:'s-aa'},{name:'bb',sname:'s-bb'},{name:'cc',sname:'s-cc'}];
}

Note: You cam find the code in this link=> STACKBLITZ DEMO LINK.

Upvotes: 2

Related Questions