首页 > 解决方案 > 将对象传递给路由器中的另一个组件

问题描述

我有一个像这样的 todoDetail 组件:

<mat-card class="todos" [class.done]="todo.done === true">

  <h3>
    <input (change) = "done(todo.id)" [checked]="todo.done" type="checkbox"/>
    <a [title]="todo.name + ' details'" >
      {{ todo.name }}
    </a>
    <button (click)="delete(todo.id)" class="del" mat-mini-fab color="warn" aria-label="Delete todo">
      x
    </button>
    <button routerLink="/editTodo" class="edit" mat-mini-fab color="accent" aria-label="Edit todo">
      Edit
    </button>
  </h3>
  <p>{{todo.urgency}}</p>
  <p *ngIf="todo.description">
    Description: {{ todo.description }}
  </p>
</mat-card>
<br>

我想要的是当我单击编辑按钮时,它会带我进入编辑待办事项屏幕,这是添加待办事项屏幕,但已填充待办事项的值。我指定了以下路线:

{ path: 'addTodo', component: AddTodoComponent },
{ path: 'editTodo', component: AddTodoComponent },

单击编辑时,如何将待办事项数据传递给该组件?我是 Angular 的新手,所以我希望这是有道理的。谢谢!

标签: angularangular-ui-router

解决方案


您可以将路由绑定到控制器中的函数并将其他可选参数发送给接收者。尝试以下

app.component.html

<h3>
  <input [(ngModel)]="todo.done" type="checkbox"/>
  <a [title]="todo.name + ' details'" >
    {{ todo.name }}
  </a>
  <button routerLink="/dashboard">
    Cancel edit
  </button>
  <button (mouseup)="gotoEdit()">        <!-- binding to a function instead of directly routing here -->
    Edit todo
  </button>
</h3>
<p>Urgency: {{todo.urgency}}</p>
<p *ngIf="todo.description">
  Description: {{ todo.description }}
</p>

<router-outlet></router-outlet>

app.component.ts

import { Router } from '@angular/router';

export class AppComponent  {
  todo = {
    done: true,
    id: '2',
    name: 'Groceries',
    urgency: 'high',
    description: 'Get groceries immediately'
  }

  constructor(private _router: Router) { }

  gotoEdit() {
    this._router.navigate(['/editTodo', {todo: JSON.stringify(this.todo)}]);
  }
}

并使用 Angular 在收件人中检索它ActivatedRoute

编辑todo.component.ts

import { ActivatedRoute } from '@angular/router';

export class EditTodoComponent implements OnInit {
  todo: any;
  constructor(private _actRoute: ActivatedRoute) { }

  ngOnInit() {
    this.todo = JSON.parse(this._actRoute.snapshot.paramMap.get('todo'));
  }
}

编辑todo.component.html

<ng-container *ngIf="todo">
  Got 'todo' object from parent:
  <pre>{{ todo | json }}</pre>
</ng-container>

这是我用作参考的路由配置

app.module.ts

import { RouterModule, Routes } from '@angular/router';

const appRoutes: Routes = [
  { path: '', component: DashboardComponent },
  { path: 'dashboard', component: DashboardComponent },
  { path: 'editTodo', component: EditTodoComponent }
];

@NgModule({
  imports:      [ BrowserModule, FormsModule, RouterModule.forRoot(appRoutes) ],
  ...
})

工作示例:Stackblitz


推荐阅读