Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/ant/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Angular 2中使用@Input属性_Angular - Fatal编程技术网

在Angular 2中使用@Input属性

在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

下面是我的示例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值

如果要检测传递的@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吗?