繁体   English   中英

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

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

我创建了一个下拉组件,它具有一些我不理解的奇怪行为。 多个下拉组件共享对[items] @Input()的相同引用。 因此,当我添加标题时,标题会添加到相同的[items]数组中。

*我刚刚意识到问题出在哪里,但觉得我仍然应该发布。

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

为什么会这样呢?

基本上, players属性是两个下拉部件之间的相同。 我在想象将players的副本传递到组件中,这是错误的。

解决此问题的两种方法:

  1. DropdownComponent复制数组
  2. 始终使用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>

暂无
暂无

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

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