2017-07-14 34 views
0

我创建了一个下拉组件,它有一些我不明白的奇怪行为。多个下拉组件与[items]@Input()共享相同的参考。所以当我添加标题时,标题会添加到相同的[items]数组中。Angular(Angular4)下拉组件@Input和ngOnInit问题

*我刚刚意识到问题所在,但感觉还是应该发表。

DropdownComponent.ts

@Component({ 
    selector: 'dropdown', 
    templateUrl: './dropdown.component.html' 
}) 
export class DropdownComponent implements OnInit { 
    @Input() items: DropdownItem[]; 
    @Input() caption: string; 

    ngOnInit() { 
     this.items.unshift(new DropdownItem(undefined, this.caption)); 
    } 
} 

其他组件的HTML

<dropdown [input]="players" [caption]="'Player One'"></dropdown> 
<dropdown [input]="players" [caption]="'Player Two'"></dropdown> 

所得的下拉列表两个下拉菜单

0. Player Two (caption) 
1. Player One (caption) 
2. Alex 
3. John 
4. Steve 

这是怎么发生的?

回答

0

基本上,这两个下拉组件之间的players属性是相同的。我想象一下players被传入组件的副本,这是错误的。

两种方法来解决这个:

  1. 请在DropdownComponent
  2. 阵列的副本总是使用create在组件阵列的拷贝DropdownComponent

溶液1

@Component({ 
    selector: 'dropdown', 
    templateUrl: './dropdown.component.html' 
}) 
export class DropdownComponent implements OnInit { 
    @Input() items: DropdownItem[]; 
    @Input() caption: string; 

    ngOnInit() { 
     this.items = this.items.slice(); 
     this.items.unshift(new DropdownItem(undefined, this.caption)); 
    } 
} 

解决方案2

<dropdown [input]="playersForPlayerOne" [caption]="'Player One'"></dropdown> 
<dropdown [input]="playersForPlayerTwo" [caption]="'Player Two'"></dropdown>