根据@Input

时间:2017-04-22 02:32:30

标签: angular

我在一个组件中有一个数组,它在Init期间被初始化。基于@input值,需要修改数组。在onChanges期间,数组似乎是空的。如何实现这一目标?

export class SomeComponent implements OnInit, OnChanges {
@Input()
pickedStudents: Student[] = [];
studentSubscription: Subscription;
students: Student[] = [];
constructor(private studentService: StudentService) {
}
ngOnInit() {
    this.studentSubscription = this.studentService.getStudents().subscribe(a => this.students = a);
}
ngOnChanges() {
    if (this.pickedStudents && this.pickedStudents.length) {
        //This is for instance. The problem is students seem to be empty here.
        this.students.splice(this.students.indexOf(this.pickedStudents[0]), 1);
    }
}
ngOnDestroy() {
    this.studentSubscription.unsubscribe();
}
}

1 个答案:

答案 0 :(得分:0)

只需在ngOnChanges中添加一个条件,如下所示

ngOnChanges(){
    if(this.arrayName && this.arrayName.length){
            your operation
    }
}