【问题标题】:Angular Material: In my mat-selection-list, I'm trying to dynamically create mat-list-options with an array of objects but I'm getting an error?Angular Material:在我的 mat-selection-list 中,我正在尝试使用一组对象动态创建 mat-list-options 但出现错误?
【发布时间】:2020-02-28 22:10:53
【问题描述】:

我遇到了一个奇怪的问题,我似乎无法用 mat-list-option 填充材料 mat-selection-list,这些材料是用对象而不是字符串数组创建的。我收到此错误:

ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

这是我的相关代码:

@ViewChild("tagsList") tagsList
  public tags: any = [];
  public selectedTags: any = [];

  ngOnInit() {}



     constructor(
        private utilitiesService: UtilitiesService,
        private tagsService: TagsService,
        public dialogRef: MatDialogRef<AccountTagsAssociatorComponent>,
        @Inject(MAT_DIALOG_DATA) public data
      ) {
        this.selectedTags = data.tags
        this.tagsService.getAll().then(tags => {
          this.tags = tags.docs;
        })
      }

      selectOption(options) {
        this.selectedTags = this.tagsList.selectedOptions.selected.map(selectedOption => {
          return selectedOption.value
        })
      }

在我的 HTML 中:

<mat-selection-list
    (selectionChange)="selectOption($event)"
     #tags >
    <mat-list-option [value]="tag.id" [selected]="selectedTags && selectedTags.indexOf(tag.id) > -1" *ngFor="let tag of tags; let i = index">
      {{tag.name}}
    </mat-list-option>
  </mat-selection-list>

我在这里遗漏了什么明显的东西吗?

编辑:我已经更新了我的代码以显示更多正在发生的事情。我与组件中的#tagsthis.tags 发生了一些冲突,所以我更改了它们。但是,这仍然没有解决我的问题:/

【问题讨论】:

  • 你的#tags 模板变量怎么了?您是否还有冲突的组件中的 tags 属性?
  • 也许还显示标签数组/对象的结构?

标签: angular angular-material material-design


【解决方案1】:

使用 KeyValue 管道迭代对象:

<div *ngFor="let item of object | keyvalue">
  {{item.key}}:{{item.value}}
</div>

https://angular.io/api/common/KeyValuePipe

然后您可以从值访问对象属性,例如item.value.prop1

【讨论】:

    猜你喜欢
    • 2021-09-02
    • 2019-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-04
    • 2019-11-02
    • 1970-01-01
    相关资源
    最近更新 更多