传递给子组件的原始值在Angular 2的构造函数中是未定义的

时间:2016-06-20 15:02:07

标签: input angular components

我对棱角2很新。 我需要创建一个用户个人资料图片的可重用组件,它有2个高度和宽度输入,最后代表一个正确大小的图片。

我在parent.html中的组件调用:

<user-profile-pic [height]="50" [width]="50" [counterValue]="myValue"></user-profile-pic>

我的组件user-profile-pic:

import {Component,Input} from '@angular/core';

@Component({
  selector : 'user-profile-pic',  
  template: '<img src="http://to/picture.png"> ',
  inputs:['width','height']
})

export class UserProfilePic {
    /*
    @Input() height : String;
    @Input() width : String;
*/
public height:String;
public width:String;
  constructor() {
      console.log("This is the height ",this.height," And the width : ",this.width);
  }

}

控制台在高度和宽度上记录我未定义的内容。 有什么建议 ?

2 个答案:

答案 0 :(得分:2)

尚未在构造函数中设置输入。它们是第一次调用ngOnChanges()时设置的(每次更新都需要调用)。在第一次调用ngOnInit()后调用ngOnChanges()

只需将代码更改为

即可
export class UserProfilePic {
    /*
    @Input() height : String;
    @Input() width : String;
*/
public height:String;
public width:String;
ngOnInit() {
      console.log("This is the height ",this.height," And the width : ",this.width);
  }
}

从您的示例看,您的组件似乎也缺少counterValue输入。

答案 1 :(得分:2)

试试:

import {Component,Input, OnInit} from '@angular/core';

@Component({
  selector : 'user-profile-pic',  
  template: '<img src="http://to/picture.png"> '
})

export class UserProfilePic implements OnInit {
    @Input() height : String;
    @Input() width : String;

  ngOnInit() {
      console.log("This is the height ",this.height," And the width : ",this.width);
  }

}