简体   繁体   English

Angular(Angular4)下拉组件@Input和ngOnInit问题

[英]Angular (Angular4) Dropdown Component @Input and ngOnInit issue

I created a dropdown component that has some strange behavior that I do not understand. 我创建了一个下拉组件,它具有一些我不理解的奇怪行为。 Multiple dropdown components share the same reference to the [items] @Input() . 多个下拉组件共享对[items] @Input()的相同引用。 So when I add a caption, the caption adds to the same [items] array. 因此,当我添加标题时,标题会添加到相同的[items]数组中。

*I just now realized what the problem is but feel like I should still post. *我刚刚意识到问题出在哪里,但觉得我仍然应该发布。

DropdownComponent.ts 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));
    }
}

Other Component Html 其他成分HTML

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

Resulting Dropdown List for both dropdowns 两个下拉列表的结果下拉列表

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

Why is this happening? 为什么会这样呢?

Basically, the players property is the same between both dropdown components. 基本上, players属性是两个下拉部件之间的相同。 I was imagining a copy of players being passed into the component, which is wrong. 我在想象将players的副本传递到组件中,这是错误的。

Two ways to fix this: 解决此问题的两种方法:

  1. Make a copy of the array in DropdownComponent DropdownComponent复制数组
  2. Always create copies of arrays in the component using DropdownComponent 始终使用DropdownComponent在组件中创建数组的副本

Solution 1 解决方案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));
    }
}

Solution 2 解决方案2

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM