以下是我的示例Angular 2组件代码
@Component({
selector: 'author-edit',
templateUrl:'./author/edit'
})
export class AuthorEditComponent implements OnInit{
@Input() author: AuthorModel;
fg: FormGroup;
constructor(
public formBuilder: FormBuilder
) {}
ngOnInit() {
alert(this.author.id); // ERROR Cannot read property 'id' of undefined
}
}
}
此组件以下面提到的方式从父组件中使用
<author-edit [author]="editAuthor"></author-edit>
在上面的代码中,为什么我无法访问“author”输入属性的this.author.id值。
答案 0 :(得分:0)
如果要检测传递的@Input()参数,请以这种方式使用OnChange抽象类而不是OnInit:
export class AuthorEditComponent implements OnChanges{
@Input() author: AuthorModel;
fg: FormGroup;
constructor(
public formBuilder: FormBuilder
) {}
ngOnChanges(changes:{[propName: string]: SimpleChange}): any {
if(changes['author'] && this.author) {
alert(this.author.id);
}
}
}
您无法确定在调用ngOnInit时传递@Input()值