我刚刚开始学习Angular,然后按照this youtube tutorial开始学习。但是,@ Input似乎在这里不起作用。这是用于存储数据的模型类:
Todo.ts:
export class Todo {
id: number;
title: string;
complete: boolean;
optional?: string;
}
Todos组件以及数据: todos.component.ts
import { Component, OnInit } from '@angular/core';
import {Todo} from '../../models/Todo';
@Component({
selector: 'app-todos',
templateUrl: './todos.component.html',
styleUrls: ['./todos.component.css']
})
export class TodosComponent implements OnInit {
todos: Todo[];
constructor() { }
strTest = 'A test string';
ngOnInit(): void {
this.todos = [
{
id: 1,
title: 'One',
complete: false
},
{
id: 2,
title: 'two',
complete: true,
optional: 'an optional item'
},
{
id: 3,
title: 'three',
complete: false
}
];
}
}
todos.component.html
<p>todos from local class</p>
<!-- Working -->
<ul *ngFor='let td of todos'>
<li>{{td.title}}</li>
</ul>
<p> From todo-item class</p>
<!-- Not Working -->
<app-todo-item *ngFor="let todo of todos" [todos]="todo" > </app-todo-item>
以下是定义选择器app-todo-item 的地方,并执行Todo的@Input:
todo-item.component.ts
import { Component, OnInit, Input} from '@angular/core';
import { Todo } from 'src/app/models/Todo';
@Component({
selector: 'app-todo-item',
templateUrl: './todo-item.component.html',
styleUrls: ['./todo-item.component.css']
})
export class TodoItemComponent implements OnInit {
@Input() todos: Todo;
constructor() {
console.log(this.todos.title);
}
ngOnInit(): void {
}
}
和 todos-item.component.html ,应该显示这些值
<div>
<p> {{ todos.title }} </p>
</div>
我在这里找不到丢失的东西。 请帮忙.. 谢谢
答案 0 :(得分:2)
根据Angular Docs,ngOnChanges
用于“当Angular(重新)设置数据绑定输入属性时响应。该方法接收当前和先前属性值的SimpleChanges对象。在ngOnInit()
之前以及每当一个或多个数据绑定输入属性更改时调用。” ,因此开始检查数据的好地方将是ngOnInit生命周期挂钩
export class TodoItemComponent implements OnInit {
@Input() todos: Todo;
constructor() {
/*
Don't access, initialize, modify at constructor.
Misko Hevery, Angular team lead, explains why you should avoid complex constructor logic.
Link --> http://misko.hevery.com/code-reviewers-guide/flaw-constructor-does-real-work/
*/
//console.log(this.todos.title);
}
ngOnInit(): void {
console.log(this.todos.title);
}
}
答案 1 :(得分:2)
在模板(todos-item.component.html
)中使用可选链接运算符。如果todos
在开始时为null / undefined,则可以中断模板渲染(无法从undefined访问title
),并导致不可恢复的javascript错误,该错误将阻止该组件中的任何其他工作。添加此内容:
<div>
<!-- NOTICE THE "?" after todos -->
<p> {{ todos?.title }} </p>
</div>