我可以在视图中检索值,但不能在construtor中检索。 我的组件是在ngFor中,我想编辑独立的每个项目。这就是我创建子组件的原因
<li style="list-style-type: none;" *ngFor="let event of item.Events">
... <child-component [demo]="event"></child-component>
在子组件中: 我可以在视图中显示demo的结果,但我无法在构造函数中检索它以便能够操作它
@Component({
selector: 'child-component',
queries: {
content: new ViewChild('content')
},
templateUrl: 'build/pages/dashboard/timeline/timeline-feeling/index.html',
...
inputs: ['demo'],
...
})
export class TimelinFeeling{
static get parameters () {
return [];
}
constructor () {
this.demo = demo;
console.log(this.demo); //return undefined
}
答案 0 :(得分:1)
声明属性(TypeScript要求)并用@Input
(角度要求)装饰它:
import { Input, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'child-component',
templateUrl: 'build/pages/dashboard/timeline/timeline-feeling/index.html',
...
})
export class TimelinFeeling{
@Input() public demo = null;
@ViewChild('content') content: ElementRef;
static get parameters () {
return [];
}
ngOnInit () {
this.demo = demo;
console.log(this.demo); //return undefined
}
最后,请检查ngOnInit
中的值。
答案 1 :(得分:0)
尚未在构造函数中设置输入值。请改用ngOnInit()
:
ngOnInit () {
console.log(this.demo); //return undefined
}