在Angular 2中使用@Input属性
下面是我的示例Angular 2组件代码在Angular 2中使用@Input属性,angular,Angular,下面是我的示例Angular 2组件代码 @Component({ selector: 'author-edit', templateUrl:'./author/edit' }) export class AuthorEditComponent implements OnInit{ @Input() author: AuthorModel; fg: FormGroup; constructor( public formBuilder: FormBu
@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值 如果要检测传递的@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);
}
}
}
您无法确定@Input()值是在调用ngOnInit时传递的editAuthor到底是什么?
editAuthor
未在父范围中设置它是类型为“AuthorModel”的对象根据您提供的示例,我们将无法确定问题仅测试您的组件,它工作正常。所以我认为editAuthor周围出了点问题。您确定AuthorModel及其实例包含id吗?