首页 > 解决方案 > 当我使用 Angular 单击以下项目结构的编辑按钮时,如何填充反应式表单?

问题描述

我正在使用 Angular 和响应式表单创建一个简单的待办事项应用程序,当在以下项目结构中单击“编辑”按钮时,我无法弄清楚如何填充表单。

项目结构:

所以 task-details.component.html 包含所有待办事项的列表,每个待办事项都有“编辑”和“删除”按钮。

这是我的 task-details.component.html

<app-task-detail-form></app-task-detail-form>

<ul>
   <li *ngFor="let t of service.listOfItems">
       {{t.title}} = {{t.isCompleted}} 
       <button (click)="onDelete(t.taskId)">Delete</button> 
       <button (click)="populate(t)">Edit</button> 
   </li>  
</ul>

我的问题是:

当我单击 task-details.component.ts 中的 populate(t) 时,如何在 task-details-form.component.html 中填充反应式表单。我知道我必须将“t”从 task-details.component.html 发送到 task-details-form.component.html,但是当我有上述项目结构时,我该怎么做呢?

标签: angularcrudedit

解决方案


您可以将待办事项<app-task-detail-form>作为输入传递给

任务详细信息.component.html

<app-task-detail-form [todo]="selectedTodo"></app-task-detail-form>

任务详细信息-form.component.ts

export class TaskDetailFormComponent {

@Input() todo: Todo;

任务详细信息.component.ts

selectedTodo: Todo;
populate(todo:Todo){
   this.selectedTodo = todo;
   //... the rest of your code in populate
}

最后的话

项目结构与这里的任何解决方案都无关。只要您的组件在 app.module.ts 中声明,它们就可以在任何地方。


推荐阅读