简体   繁体   中英

How to access Input data passed from parent component in Angular 2

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() {

  }
}

Thierry is correct wrt 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 .

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM