0

I have playlist component as a child Component, the parent pass in an input 'playlist' which is an Object of Array.

  playList: {
    headerPlaylists: Array<any>,
    bodyPlaylists: Array<any>
  } = {
    headerPlaylists: [],
    bodyPlaylists: []
  }

The Child Component as below

@Component({
  selector: 'playlist',
  styleUrls: ['app/channel/playlist/playlist.css'],
  templateUrl: 'app/channel/playlist/playlist.html',
  directives: [VideoItemComponent],
  inputs: ['playlist']
})

My question is, in my class, how do I get access to the inputs passed in from it's parent component, say, simply console.log(playlist), is there a way to do that?

export class PlaylistComponent {

  constructor() {

  }
}

2 Answers 2

2

Thierry is correct w.r.t. the availability of inputs across the lifecycle, but how this works is much clearer if you use @Input() on the field rather than inputs in the metadata.

@Component({
  selector: 'playlist',
  styleUrls: ['app/channel/playlist/playlist.css'],
  templateUrl: 'app/channel/playlist/playlist.html',
  directives: [VideoItemComponent],
 // inputs: ['playlist'] // would be redundant
})
class PlaylistComponent implements OnInit {
  @Input() playlist: YourPlaylistType; // i.e. the data structure you posted

  ngOnInit(){
     // use this.playlist 
  }
}

Note that, largely for this reason, specifying inputs via @Input() is preferred over using inputs as per the ng2 style guide.

Sign up to request clarification or add additional context in comments.

Comments

1

The playlist property will be available within the ngOnInit hook method of the component:

export class PlaylistComponent {
  playlist: any; // or a specify type instead of any

  constructor() {
    console.log(this.playlist); // is null
  }

  ngOnInit() {
    console.log(this.playlist); // is set
  }
}

In the constructor, the property isn't set yet.

For more details, see this page about lifecycle hooks:

2 Comments

You still need to have a playlist property on the class or this won't compile
You're right. I was focused on when displaying the property, so I forgot the property declaration. I updated my answer. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.