title: Angular: In which lifecycle hook is input data available to the Component
body: <p>I have a component which receives an array of <code>image</code> objects as <code>Input</code> data. </p>
  
  <pre><code>export class ImageGalleryComponent {
    @Input() images: Image[];
    selectedImage: Image;
  }
  </code></pre>
  
  <p>I would like when the component loads the <code>selectedImage</code> value be set to the first object of the <code>images</code> array. I have tried to do this in the <code>OnInit</code> lifecycle hook like this:</p>
  
  <pre><code>export class ImageGalleryComponent implements OnInit {
    @Input() images: Image[];
    selectedImage: Image;
    ngOnInit() {
      this.selectedImage = this.images[0];
    }
  }
  </code></pre>
  
  <p>this gives me an error <code>Cannot read property '0' of undefined</code> which means the <code>images</code> value isn't set on this stage. I have also tried the <code>OnChanges</code> hook but I'm stuck because i can't get information on how to observe changes of an array. How can I achieve the expected result? </p>
  
  <p>The parent component looks like this:</p>
  
  <pre><code>@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 =&gt; {
       this.profile = profile;
       this.images = profile.images;
       for (var album of profile.albums) {
         this.images = this.images.concat(album.images);
       }
      }, error =&gt; this.errorMessage = &lt;any&gt;error
     );
   }
  }
  </code></pre>
  
  <p>The parent component's template has this</p>
  
  <pre><code>...
  &lt;image-gallery [images]="images"&gt;&lt;/image-gallery&gt;
  ...
  </code></pre>