简体   繁体   中英

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM