我有一个组件,它接收一组image
对象作为Input
数据。
export class ImageGalleryComponent {
@Input() images: Image[];
selectedImage: Image;
}
我想在组件加载时将selectedImage
值设置为images
数组的第一个对象。我试图在OnInit
生命周期钩子中这样做:
export class ImageGalleryComponent implements OnInit {
@Input() images: Image[];
selectedImage: Image;
ngOnInit() {
this.selectedImage = this.images[0];
}
}
这给了我一个错误Cannot read property '0' of undefined
,这意味着该images
值未在此阶段设置。我也试过这个OnChanges
钩子,但我被卡住了,因为我无法获得有关如何观察数组变化的信息。我怎样才能达到预期的结果?
父组件如下所示:
@Component({
selector: 'profile-detail',
templateUrl: '...',
styleUrls: [...],
directives: [ImageGalleryComponent]
})
export class ProfileDetailComponent implements OnInit {
profile: Profile;
errorMessage: string;
images: Image[];
constructor(private profileService: ProfileService, private routeParams: RouteParams){}
ngOnInit() {
this.getProfile();
}
getProfile() {
let profileId = this.routeParams.get('id');
this.profileService.getProfile(profileId).subscribe(
profile => {
this.profile = profile;
this.images = profile.images;
for (var album of profile.albums) {
this.images = this.images.concat(album.images);
}
}, error => this.errorMessage = <any>error
);
}
}
父组件的模板有这个
...
<image-gallery [images]="images"></image-gallery>
...