使用带有对象数组的@input的Angular 4.4.3组件导致浏览器无法响应/初始化

时间:2017-09-22 22:07:26

标签: angular angular-material angular-components

我正在尝试构建一个在其模板中使用两个材质设计组件的新组件。我的想法是,我将有一个新组件,从md-select中选择一个项目后,将该项目添加到md-chip-list,然后清除选择并允许您将其他项目添加到md-chip-list。

组件应该使用optionsList,它是一个对象数组,如:

[{ viewValue: "Eve",value:"E" }, { viewValue: "Bob", value:"B" }, { viewValue: "Alice", value:"A" }]

组件和模板如下所示。

import { Component, OnInit, Inject } from '@angular/core';
import { Input } from '@angular/core';


@Component({
    selector: 'chip-set-select',
    templateUrl: './ChipSetSelect.component.html',
    styleUrls: ['./ChipSetSelect.component.scss']
})

export class ChipSetSelectComponent implements OnInit {
    @Input() optionList: any[];//TODO can we use generic instead of any? Really we want all these arrays to be of the same type, but we don't know the type in advance.
    //optionList: any[];//TODO can we use generic instead of any? Really we want all these arrays to be of the same type, but we don't know the type in advance.
    @Input() selectedItems: any[];
    selectValue: any;

    // Use "constructor"s only for dependency injection
    constructor() { }

    // Here you want to handle anything with @Input()'s @Output()'s
    // Data retrieval / etc - this is when the Component is "ready" and wired up
    ngOnInit() {
        //this.optionList = ["Susan", "Bob", "Alice"];
        //this.optionList = [{ viewValue: "Susan",value:"S" }, { viewValue: "Bob", value:"B" }, { viewValue: "Alice", value:"A" }];
    }
}
{{optionList}}
<div *ngFor="let option of optionList">value: {{option.value}} viewValue: {{option.viewValue}}</div>
<md-select class="fullWidth" placeholder="Select Funder(s)" [(ngModel)]="selectValue">
  <md-option *ngFor="let option of optionList" [value]="option.value">
    {{option.viewValue}}
  </md-option>
</md-select>
{{selectValue}}
<md-chip-list><md-chip *ngFor="let item of selectedItems">{{item}}</md-chip></md-chip-list>

然后我使用如下组件:

<chip-set-select [optionList]="getOptionList()" [selectedItems]="getSelectedFunders()"></chip-set-select>

在选择列表显示为已填充之前,事情最终会挂起。 * ngFor或let声明可能出现的问题?浏览器控制台中不会显示任何错误。

奇怪的是,如果我删除了optionList属性并删除组件中的@input并测试在组件的ngOnInit期间初始化的相同对象数组,则选择列表将按预期填充,即使它是完全相同的对象数组。

同样,如果我使用一个字符串数组传递给[optionList]并相应地修改其他代码......一切都可以用字符串值填充选择选项。

知道出了什么问题或为什么单独工作的元素在创建最终产品时会造成问题?

1 个答案:

答案 0 :(得分:1)

当我试图诊断/解决非常类似的问题时,我偶然发现了这个问题。在我的情况下,浏览器也冻结了。这是无限循环的经典症状!导致其他事件触发的一个事件。我未能确切地找到它发生的确切位置但是后续修复解决了它(与您的相似)。

函数调用似乎是导致循环的罪魁祸首。使用引用数组/对象替换函数调用。使用两个单独的列表/数组来存储选项和选择。防爆。 ComputerPlayer computerPlayer = new ComputerPlayer(this); 用于选择选项,options[]用于存储所选选项。每当选择一个选项时,都会调用一个函数(添加?)将该项添加到chips[]。添加chips[]后,还会有一个chips[],它会反映在用户界面上。