如何将对象从一个组件绑定到另一个组件



我试着学习Angular8,但现在我在将对象或值从一个组件传递到另一个组件的代码方面遇到了问题。

我尝试过@Input,但结果是未定义的。

我有一个组件,它返回两个输入的结果[(ngModel(];标题和描述。在组件应用程序之后添加项目

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

应用程序添加项目的模板html。

add-todo项是第二个组件。该组件生成项目视图。

<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>

在组件应用程序todo项目之后

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

谢谢你的回答。

export class ViewItemComponent {
@Input() itemTitle: string;
item: TodoItem = {
list: 'example',
id: 1,
title: this.itemTitle,
description: 'an example list item for the view model',
completed: false,
};
}

在上面的代码中,在文本框中输入任何文本之前,"item"的值被设置为对象文字。这意味着在进行任何输入绑定之前,"item.title"将被设置为未定义。

如果将itemTitle设置为setter,则可以在每次用户向文本字段中输入时设置"item.title"的值。

@Input()
set itemTitle(value) {
this.item.title = value;
}
item: TodoItem = {
list: 'example',
id: 1,
title: 'Default Title',
description: 'an example list item for the view model',
completed: false,
};

或者,您可以在添加项组件中绑定整个todo项对象。

// add-item.component.html
<div class="item-content" *ngFor="let item of items">
<app-todo-item [item]="item"></app-todo-item>
</div>
// view-item.component.ts
export class ViewItemComponent {
@Input()
item: TodoItem;
}

并在模板中使用属性绑定。

// view-item.component.html
<p>ItemID-{{ item.id }}</p>
<p>{{ item.title }}</p>
<p>{{ item.description }}</p>

https://stackblitz.com/edit/angular-gzefwj

最新更新