2017-03-03 48 views
0

下面使用@input屬性是我的樣品角2分量代碼在角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

editAuthor究竟是什麼? –

+0

'editAuthor'未在父範圍內設置 – VadimB

+0

它是「AuthorModel」類型的對象 – refactor

回答

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); 
     } 
    } 
} 

你不能確保@input()值中傳遞ngOnInit被調用的時刻