在Angular 2中使用@Input属性

时间:2017-03-03 14:45:59

标签: angular

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

1 个答案:

答案 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()值

相关问题