角度:其中生命周期钩子是组件可用的输入数据
2022-08-30 05:35:25
我有一个组件,它接收一个对象数组作为数据。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>
...