如何将数据绑定到 Angular 2 中的多个嵌套组件?

Posted

技术标签:

【中文标题】如何将数据绑定到 Angular 2 中的多个嵌套组件?【英文标题】:How bind data to multiple nested components in Angular 2? 【发布时间】:2018-04-16 09:27:48 【问题描述】:

在使用以下结构的 Angular 4 应用程序中:

ComponentA 从服务中获取以下模型:

class ViewModel 
    public someBool: boolean;                
    public someNumber: number;               
    public someArray: CFlightClassQuote[];   
    public someOtherNumber: number;               
    public someString: string; 

ComponentA 类:

export class ComponentA implements OnInit 
  searchResult: Array<ViewModel>;

  constructor(private searchResultService: SearchResultService, private router: Router)  

  ngOnInit(): void 
    this.searchResultService.getSearchResultTable('hash').then( result => 
      this.searchResult = result;
    );
  

ComponentA 模板:

*some html*
    <div>
      <app-component-b [dataSet]="searchResult"></app-component-b>
    </div>
*some html*

在组件 B 中我使用 *ngFor

ComponentB 模板:

<div class="results-table" *ngFor="let item of dataSet">
   <span>item.someString</span>
   <app-component-c [dataSet]="item.SomeArray"></<app-component-c>

another html
</div>

ComponentB 类:

export class ComponentB implements OnInit 
  @Input() dataSet: Array<ViewModel>;

  constructor()  

  ngOnInit() 
  

数据已正确绑定到 ComponentB,但 ComponentC 仍然为空。 我认为我在这个字符串中错了:

<app-component-c [dataSet]="item.SomeArray"></<app-component-c>

并且数据应该像 ComponentA 和 ComponentB 一样被传递到 ComponentC 中。

这应该如何正确完成?

【问题讨论】:

你能创建一个 plunker 来重现这个问题吗?还将所有模板 HTML 添加到 post 【参考方案1】:

假设您的问题拼写正确,并且假设您的组件 C 的定义类似于组件 B,但引用了正确的数组类型 (CFlightClassQuote),则当您访问引用的属性时,您的模板中有错字到数组。

这个,

<app-component-c [dataSet]="item.SomeArray"></<app-component-c>

应该是,

<app-component-c [dataSet]="item.someArray"></<app-component-c>
                                ^^^
                                here 

【讨论】:

我们只是在组件 c 的 ts 文件中传递数据集,输入正确吗?

以上是关于如何将数据绑定到 Angular 2 中的多个嵌套组件?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Angular 中绑定多个插值模板?

在新的 Angular 2 表单中将 NgModel 绑定到 FormControl

如何告诉 SwiftUI 视图绑定到多个嵌套的 ObservableObject

如何正确地将数据绑定到 Angular2 中的单选按钮?

Angular 2 - 单元测试绑定到嵌套的自定义表单控件

Angular2,Ionic2:如何使用 ngModel 对嵌套 *ngfor 中的单选按钮进行 2way 绑定?