gpt4 book ai didi

angular - angular2 中未定义的组件参数

转载 作者:搜寻专家 更新时间:2023-10-30 21:30:00 26 4
gpt4 key购买 nike

试图弄清楚这一点,但不能......也许这是显而易见的事情:

在 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组件参数绑定(bind):

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生命周期钩子(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.

您可以像这样实现 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);
}
}

关于angular - angular2 中未定义的组件参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41864655/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com