【问题标题】:How to access Input data passed from parent component in Angular 2如何访问从Angular 2中的父组件传递的输入数据
【发布时间】:2016-04-19 21:07:24
【问题描述】:

我有播放列表组件作为子组件,父组件传入一个输入“播放列表”,它是一个数组对象。

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

子组件如下

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

我的问题是,在我的课堂上,我如何访问从它的父组件传入的输入,比如简单的 console.log(playlist),有没有办法做到这一点?

export class PlaylistComponent {

  constructor() {

  }
}

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    蒂埃里是正确的 w.r.t.整个生命周期中输入的可用性,但是如果您在字段中使用@Input() 而不是在元数据中使用inputs,那么它的工作原理会更加清晰。

    @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 
      }
    }
    

    请注意,主要出于这个原因,通过@Input() 指定输入比使用ng2 style guide 输入更可取。

    【讨论】:

      【解决方案2】:

      playlist 属性将在组件的 ngOnInit 钩子方法中可用:

      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
        }
      }
      

      在构造函数中,该属性尚未设置。

      有关更多详细信息,请参阅有关生命周期挂钩的页面:

      【讨论】:

      • 你仍然需要在类上有一个playlist 属性,否则这将无法编译
      • 你是对的。我在显示属性时专注于,所以我忘记了属性声明。我更新了我的答案。谢谢!
      猜你喜欢
      • 2017-01-25
      • 1970-01-01
      • 2017-11-09
      • 2017-08-30
      • 2019-01-06
      • 2020-04-05
      • 2017-06-25
      • 2020-11-02
      • 2022-01-19
      相关资源
      最近更新 更多