2017-09-22 59 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中無限循環的原因。不知道爲什麼該方法調用適用於一個字符串數組,但不適用於一組對象。這似乎很奇怪。 –