传递数据时@Input不工作angular5

时间:2017-12-10 15:04:58

标签: angular

我要做的是从app.component.ts传递一个名为 user 的值,并设置名为 user <的userComponent的属性/ strong>。

以下是我的代码:

app.component.ts

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

@Component({
  selector: 'my-app',
  template: `
    <userComponent [user]="user"></userComponent>
  `
})

export class AppComponent {
  user: User= {name:'martin','age':22};
  constructor(){  }
}

user.component.ts

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

@Component({
  selector: 'nextComponent',
  template: `<i> </i> `
})

export class UserComponent {

    @Input() user: User;

    constructor () {
        console.log('The value  we are receiving here is: ' + this.user)
    }

}

我在控制台中没有收到任何东西。问题是什么?

1 个答案:

答案 0 :(得分:4)

使用 ngOnInit() 代替内部构造函数

export class UserComponent {
    @Input() user:User;

    ngOnInit () {
         console.log('The value  we are receiving here is: ' + this.user);
    }
}