@Input()值未在Angular 2中定义

时间:2016-06-08 19:23:43

标签: angular

我正试图从@Input()推文中获取 isActivated 。但是当我想将 isActivated 存储到变量时会出现此错误:未定义推文。这是我的代码:(对我的英语也很抱歉)

export class SingleTweetComponent { 
    @Input() tweet;
    isActivated = tweet.isActivated;
    likeButton($event){
        this.tweet.totalLikes = this.tweet.totalLikes - 1;
    }
}

1 个答案:

答案 0 :(得分:2)

因为在您尝试使用推文时未定义推文。在计算属性时,您还没有输入数据

要解决此问题,您可以在组件的OnInit挂钩中进行修改:

export class SingleTweetComponent { 
    @Input() tweet;

    ngOnInit() {
      this.isActivated = this.tweet.isActivated;
    }

    likeButton($event) {
      this.tweet.totalLikes = this.tweet.totalLikes - 1;
    }
}