angular2, how to show the same component more than once

时间:2016-04-21 22:35:02

标签: typescript angular angular2-routing

I have a wizard component with multiple step components, these steps are routed to by the wizard component and the wizard itself is routed to from the root component. As the last step of the wizard, i need to show all the navigated steps at once for reviewing purposes with all the data that's entered while navigating them. How could i achieve this?

what I've tried:

  1. Added @Injectable() to each step component and used Angular2 injection provider, but no matter what I've tried, it always instantiates a new instance and all the data entries are gone.

  2. Passing hard-coded references around. Not only terrible and bad practice, thankfully it didn't work since you can't access prototype properties outside the component domain.

All fresh out of options. Anything is welcomed!

2 个答案:

答案 0 :(得分:1)

在服务中维护数据并将视图绑定到服务而不是组件类,然后每个组件将显示相同的数据。

@Injectable()
class SharedData {
  name:string;
}

@Component({
  selector: 'wiz-step1',
  template`
<input type="text" [(ngModel)]="sharedData.name">
`})
export class WizStep1 {
  constructor(private sharedData:SharedData) {}
}

@Component({
  selector: 'my-app',
  directives: [WizStep1],
  providers: [SharedData],
  template`
<wiz-step1></wiz-step1>
<wiz-step1></wiz-step1>
`})
export class AppComponent {}

Plunker example

有关如何使用更复杂数据的服务,请参阅

答案 1 :(得分:0)

我会使组件模型驱动(数据驱动)和重用实现。

假设您在每个步骤中都有2个步骤和1个输入,因此您可以创建模型:

border

显示每一步:

private steps = [
     {
       description: 'step 1',
       value: '0'
     },
     {
       description: 'step 2',
       value: '1'
     }
]

显示所有步骤:

component.model = this.steps[currentStep];

<component [model]="steps[currentStep]"></component>

<input [(ngModel)]="model.value">