Reputation: 2553
Trying to figure this out but can't...maybe it's something obvious:
Invocation of the 'todo' component in html:
<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 component parameter binding:
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);
}
The listName parameter is always 'undefined'. The TodoComponent gets initialized twice (since I have two lists).
What am I doing wrong here?
Any help is appreciated.
Upvotes: 3
Views: 1288
Reputation: 58400
The Input
will not be available in the constructor. You need to use the ngOnInit
lifecycle hook:
ngOnInit
is called right after the directive's data-bound properties have been checked for the first time, and before any of its children have been checked. It is invoked only once when the directive is instantiated.
You would implement OnInit
like this:
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);
}
}
Upvotes: 4