我有2个组件,
组件A:
<app-selector [test]="title"></app-selector>
export class AssignerComponent implements OnInit {
title:any = 'get';
constructor() {}
}
组件B:
export class SelectorComponent implements OnInit {
@Input() test:any;
constructor() {
console.log(this.test)
}
}
但是无法从A中获得组件B中的测试值。它是未定义的。任何人都可以建议我帮忙。谢谢。
这是通过test
输入将数据从组件A传递到组件B的正确方法。但是,你看到undefined
为this.test
的值,因为你试图从constructor
将它登录到控制台,这是在它被设置为你传递的值之前。
如果将console.log(this.test)
语句移动到ngOnInit
方法,您将看到所需的行为:
Component B:
export class SelectorComponent implements OnInit {
@Input() test:any;
constructor() {}
ngOnInit() {
console.log(this.test);
}
}
这里有关于生命周期钩子的更多信息以及Angular组件的创建方式:https://angular.io/guide/lifecycle-hooks