@input属性在角2的未定义的OnInit [英] @Input property is undefined in angular 2's onInit

查看:184
本文介绍了@input属性在角2的未定义的OnInit的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图让在构造函数或ngOnInit组件的@input价值。但它是未来的不确定的所有时间。

Trying to get the component's @Input value in constructor or ngOnInit. But it is coming as "undefined" all the time.

我更新了英雄plunker用的console.log显示问题(测试版角)。
http://plnkr.co/edit/dseNM7OTFi1VNG2Z4Oj5?p=$p$pview

I updated the hero plunker with console.log to show the issue (beta angular). http://plnkr.co/edit/dseNM7OTFi1VNG2Z4Oj5?p=preview

export class HeroDetailComponent implements OnInit {
  constructor(){
    console.log('hero', this.hero)
  }
  public hero: Hero;

  ngOnInit() {
    console.log('hero', this.hero)
  }
}

我在做什么错在这里?

What am I doing wrong here?

推荐答案

你的 ngOnInit 使用未定义的原因是因为在那里的组件被初始化你点没有在英雄对象实际上通过

The reason you're getting undefined in ngOnInit is because at the point where the component is initialised you haven't actually passed in a Hero object

<my-hero-detail [hero]="selectedHero"></my-hero-detail>

此时 selectedHero 在你的 AppComponent 没有价值,而不是以前的列表中单击事件调用 ONSELECT

At this point selectedHero has no value in your AppComponent and doesn't until the click event on the list calls the onSelect method

编辑:对不起意识到我其实没有提供修复。如果添加 ngIf 我的英雄细节

Sorry realised I didn't actually offer a fix. If you add an ngIf to my-hero-detail

<my-hero-detail *ngIf="selectedHero" [hero]="selectedHero"></my-hero-detail>

你应该这样会耽误的初始化我的英雄细节组件,你应该看到的控制台输出。这的不会的却又输出时所选择的英雄变化。

you should this will delay the initialisation of the my-hero-detail component and you should see the console output. This wont however output again when the selected hero changes.

这篇关于@input属性在角2的未定义的OnInit的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆