gpt4 book ai didi

Angular:@input 似乎不起作用

转载 作者:行者123 更新时间:2023-12-02 00:05:17 24 4
gpt4 key购买 nike


我刚刚开始学习 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>

我在这里找不到丢失的部分。请帮忙..谢谢

最佳答案

根据Angular DocsngOnChanges 用于“在 Angular(重新)设置数据绑定(bind)输入属性时响应。该方法接收一个包含当前和先前属性值的 SimpleChanges 对象。在 ngOnInit() 之前以及每当一个或多个数据绑定(bind)输入属性发生变化时调用。” , 所以开始检查数据的好地方是 ngOnInit 生命周期钩子(Hook)

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

}

阅读此 exploring angular lifecycle hooks onchanges

关于Angular:@input 似乎不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60840688/

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