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>
...
images親コンポーネントにデータがどのように入力されていますか?つまり、httpリクエスト経由ですか?もしそうなら、ImageGalleryComponent subscribe()をhttpobservableに持っている方が良いかもしれません。