对模型中的数组进行迭代

问题描述 投票:0回答:1

简介:我试图遍历作为对象的一部分返回的数组。该对象具有三个属性:2个字符串,1个数组。我想遍历我的HTML数组,但似乎无法填充它。我可以同时显示两个字符串,但是无法弄清楚如何为值迭代内部数组。

Policy.ts

import { Document } from './Document';

export interface Policy {
  insuredName: string;
  policyNumber: string;
  documents: Document[];
}

Document.ts

export interface Document {
    url: string,
    docType: string
  }

我将模型(“策略”)绑定到我的父组件中


@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.css']
})
export class SearchComponent implements OnInit {
  policy: any = {};

  constructor(private policyService: PolicyService, private alertify: AlertifyService) { }

  ngOnInit() {
  }
loadPolicy() {
    this.policyService.getPolicy(this.policy.policyNumber).subscribe((res) => {
      this.policy.insuredName = res.insuredName;
      this.policy.policyNumber = res.policyNumber;
      this.documents = res.documents;


    }, error => {
      this.alertify.error(error);
    })
  }

我将数据传递给我的子组件

Search.component.html

<app-documentList [policy]=policy></app-documentList>

然后将其绑定到子项中

export class DocumentListComponent implements OnInit {
  @Input() policy: Policy;

  ngOnInit() {

  }

但是当我最终尝试迭代时,我得到的只是第一个属性(insuredName),对于* ngFor来说什么也没有

<div>
  <div class="test">

    <p>{{policy.insuredName}}</p>
    <h2 *ngFor="let doc of policy.documents">{{doc.url}}</h2>
  </div>
</div>

arrays angular ngfor
1个回答
3
投票

尝试用this.documents = res.documents;替换this.policy.documents = res.documents;

好像您将结果绑定到错误的变量。]​​>

此外,您可能不必手动分配值。您可以执行以下操作

import { Policy } from './Policy';

@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.css']
})
export class SearchComponent implements OnInit {
  policy: Policy = {};

  constructor(private policyService: PolicyService, private alertify: AlertifyService) { }

  ngOnInit() {
  }

  loadPolicy() {
    this.policyService.getPolicy(this.policy.policyNumber).subscribe((res: Policy) => {
      this.policy = res;
    }, error => {
      this.alertify.error(error);
    });
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.