【问题标题】:ANGULAR Iterate over an Array within a Model角度迭代模型中的数组
【发布时间】:2020-03-18 21:00:02
【问题描述】:

简介: 我正在尝试遍历作为对象一部分返回的数组。该对象具有三个属性 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>

然后绑定到child中

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>

【问题讨论】:

  • 你是不是忘记了应用选择器上child的policy属性上的引号?应该是 [policy] = "policy"

标签: arrays angular ngfor


【解决方案1】:

尝试将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);
    });
  }
}

【讨论】:

  • 这两个建议都奏效了......感谢您帮助我找到我的日常“真的我错过了?!?!?”时刻。
猜你喜欢
  • 1970-01-01
  • 2020-12-15
  • 2020-10-25
  • 2021-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-13
相关资源
最近更新 更多