[英]Undefined component parameter in angular2
試圖弄清楚這一點,但不能...也許這很明顯:
調用HTML中的“ todo”組件:
<div *ngFor="let item of todoLists" class="row">
<div class="col-xl-7 col-lg-7 col-md-12 col-sm-12 col-xs-12 bottom-15">
<todo [listName]="item"></todo>
</div>
</div>
TodoComponent組件參數綁定:
export class TodoComponent {
public todoList:Array<any>;
public newTodoText:string = '';
@Input() listName: string;
constructor(private _todoService: TodoService) {
console.log("TodoComponent: constructor");
console.log("TodoComponent: listname - " + this.listName);
this.todoList = this._todoService.getTodoList(this.listName);
}
listName參數始終為“未定義”。 TodoComponent初始化兩次(因為我有兩個列表)。
我在這里做錯了什么?
任何幫助表示贊賞。
Input
將在構造函數中不可用。 您需要使用ngOnInit
生命周期掛鈎:
ngOnInit
在第一次檢查指令的數據綁定屬性之后以及在檢查其子項之前ngOnInit
調用。 實例化指令后,僅調用一次。
您可以這樣實現OnInit
:
import { OnInit } from "@angular/core";
export class TodoComponent implements OnInit {
...
constructor(private _todoService: TodoService) {
console.log("TodoComponent: constructor");
}
ngOnInit() {
console.log("TodoComponent: ngOnInit");
console.log("TodoComponent: listname - " + this.listName);
this.todoList = this._todoService.getTodoList(this.listName);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.