2017-09-22 11 views
0

我正在尝试构建一个使用其模板中的两个材质设计组件的新组件。我的想法是,我将有一个新的组件,从md-select中选择一个项目后,将该项目添加到md-chip-list,然后清除选择并允许您将其他项目添加到md-chip-list。Angular 4.4.3使用@input的组件使对象数组导致浏览器无法响应/初始化

该组件应采取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

当我试图诊断/修复非常类似的问题时,我偶然发现了这个问题。在我的情况下,浏览器也冻结。这是一个无限循环的典型症状!一起导致其他事件发生的事件。我没有找到它到底发生了什么,但下面的修复解决了它(类似于你的)。

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

+0

我以类似的方式解决了这个问题,但还没有报告过,因为我不明白是什么导致破损。我也使用了一个在ngOnInit中初始化的数组。无法找到Angular中无限循环的原因。不知道为什么该方法调用适用于一个字符串数组,但不适用于一组对象。这似乎很奇怪。 –