【问题标题】:Angular: pass dynamic values to nested components inside ngForAngular:将动态值传递给 ngFor 内的嵌套组件
【发布时间】:2021-03-04 06:23:20
【问题描述】:

我想向其发送动态值的 ngFor 循环中有一个子组件。这是我迄今为止尝试过的,但它似乎不起作用

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

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

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

</div>

在子组件中我使用@Input() 来获取值

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

我没有得到动态的名字和姓氏

任何建议都会有很大帮助。提前致谢

【问题讨论】:

  • 您编写的代码似乎是正确的。 item.firstname 可以为空吗?您还可以监视ngOnChanges@Input 参数的值。
  • @MuhammetCanTONBUL 名字和姓氏始终存在。我会检查 ngOnchanges,谢谢你的建议
  • @Exsite 请检查我的代码并告诉我它是否符合您的目的。最良好的祝愿。 :-)

标签: angular


【解决方案1】:

我想我有一个适合你的解决方案。请检查我的代码和 stackblitz 链接=>
儿童 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;
}

父 HTML:

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

父 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'}];
}

注意:您可以在此链接中找到代码=> STACKBLITZ DEMO LINK

【讨论】:

    猜你喜欢
    • 2017-11-10
    • 1970-01-01
    • 2016-11-02
    • 2021-04-26
    • 1970-01-01
    • 2016-08-31
    • 2017-11-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多