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

问题描述 投票:0回答:1

我尝试学习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();
  }

}

[的模板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, }; }
感谢您的回答。

我尝试学习Angular8,但是现在我遇到了一些问题,需要一些代码将一个对象或值从一个组件传递到另一个。我试过@Input,结果是不确定的。我有这个...

typescript object binding components angular8
1个回答
0
投票
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, }; }
© www.soinside.com 2019 - 2024. All rights reserved.