Angular 基本角度问题:@input无法从父组件获取数据

Angular 基本角度问题:@input无法从父组件获取数据,angular,Angular,对不起,这可能是一个非常愚蠢的问题,但有一天它一直困扰着我 我想从父组件导出数据 使用接口TodoItem export interface TodoItem { id: number; value: string; done: boolean; } 以及在子组件中接收数据 import { Component, OnInit, Input } from '@angular/core'; import { TodoItem } from './todo-item';

对不起,这可能是一个非常愚蠢的问题,但有一天它一直困扰着我

我想从父组件导出数据

使用接口TodoItem

export interface TodoItem {
    id: number;
    value: string;
    done: boolean;
}
以及在子组件中接收数据

import { Component, OnInit, Input } from '@angular/core';
import { TodoItem } from './todo-item'; 


@Component({
  selector: 'app-todo-items',
  templateUrl: './todo-items.component.html',
  styleUrls: ['./todo-items.component.css']
})

export class TodoItemsComponent implements OnInit {

  constructor() { }

  ngOnInit(): void {
  }

  @Input() items: TodoItem; 
}
然后我陷入了困境,我尝试了很多方法来编写html,但是什么都没有出现

<app-add-form></app-add-form>  <--! this one works-->

<app-todo-items [items]="todoItems[0]"></app-todo-items> <--! nothing shows up-->

您可以这样做:

@Input() items: TodoItem[] = [];
<app-todo-items [items]="todoItems"></app-todo-items>
然后按如下方式传入数组:

@Input() items: TodoItem[] = [];
<app-todo-items [items]="todoItems"></app-todo-items>

我的问题解决了。错误在于我没有在子组件模板中进行绑定

像这样

{{items}}

代码将像这样完整

在子组件模板中:

<ul>
<li *ngFor="let item of items">
    <label htmlFor="chk_{{item.id}}">
        <input id="chk_{{item.id}}" type="checkbox" [checked]="item.done"> {{ item.value }}
    </label>
    |
    <a href="#">刪除</a>
</li>
</ul>
<app-todo-items [items]="todoItems">
</app-todo-items>
    {{item.value}} |
在父组件模板中:

<ul>
<li *ngFor="let item of items">
    <label htmlFor="chk_{{item.id}}">
        <input id="chk_{{item.id}}" type="checkbox" [checked]="item.done"> {{ item.value }}
    </label>
    |
    <a href="#">刪除</a>
</li>
</ul>
<app-todo-items [items]="todoItems">
</app-todo-items>

如果您想使用
输入
指令将数据传递给组件,则需要在
app.component.html
中通过其引用呈现组件。您的
app.component.html
是正确的,但问题在于
Input
指令的使用。您需要提供变量的名称作为参数

@Input("items")
items: TodoItem;

在app.component.html中,如果您有子组件,您只需要实际填充已添加的属性
@Input
,这样它就类似于
,或者您想要的任何一个,因为它是一个数组。您能否共享您的app.component.html,以查看您是如何传递数据的。。。todo-items.component.html中有什么请显示todo-items.component.html您的问题不清楚。您应该指定呈现数据时遇到问题,而不是按照问题中的说明传递数据。