【发布时间】:2020-02-20 21:20:26
【问题描述】:
我尝试学习 Angular8,但是现在我遇到了一些代码,用于将对象或值从一个组件传递到另一个组件。
我已经尝试过 @Input 并且结果未定义。
我有这个组件返回,[(ngModel)] 两个输入的结果;标题和描述。 在组件 app-add-item
之后import { Component, OnInit} from '@angular/core';
@Component({
selector: 'app-add-item',
templateUrl: './add-item.component.html',
styleUrls: ['./add-item.component.scss'],
})
export class AddItemComponent implements OnInit {
items = [];
// itemList -> chenge next whit the list of lists for choice one
itemList = 'example';
itemID: number = this.items.length + 1;
itemTitle: string;
itemDescription: string;
ngOnInit() {
this.itemTitle = '';
this.itemDescription = '';
}
addItem() {
this.items.push({
list: this.itemList,
id: this.itemID,
title: this.itemTitle,
description: this.itemDescription,
completed: false,
});
this.itemID++;
this.ngOnInit();
}
}
app-add-item的模板html。
add-todo-item 是第二个组件。该组件生成项目视图。
<section class="add-item-section">
<div class="add-item-content">
<input type="text" class="add-textbox add-title" placeholder="Add the best title ever!" [(ngModel)]="itemTitle"/>
<input type="text" class="add-textbox add-description" placeholder="Add a description for the best todo item!" [(ngModel)]="itemDescription"/>
<input type="button" class="add-button" value="+" (click)="addItem()"/>
</div>
</section>
<section class="items-content">
<div class="item-content" *ngFor="let item of items">
<app-todo-item [itemTitle]= "item.title"></app-todo-item>
</div>
</section>
在组件 app-todo-item
之后import { Component, Input } from '@angular/core';
interface TodoItem {
list: string;
id: number;
title: string;
description?: string;
completed: boolean;
}
@Component({
selector: 'app-todo-item',
templateUrl: './view-item.component.html',
styleUrls: ['./view-item.component.scss'],
})
export class ViewItemComponent {
@Input() itemTitle: string;
items: TodoItem = {
list: 'example',
id: 1,
title: this.itemTitle,
description: 'an example list item for the view model',
completed: false,
};
}
感谢您的回答。
【问题讨论】:
-
我试图重新创建您上面的内容,但无法准确找出您遇到的问题。你能详细说明一下吗? stackblitz.com/edit/angular-gzefwj
-
问题是当我绑定 itemTitle 时,在浏览器视图中不显示待办事项中的标题,如果我这样做,请给我 console.log(this.itemTitle) 未定义。
标签: typescript object binding components angular8