在angular2中实现向导?

时间:2016-04-12 16:29:21

标签: angular

我需要在angular2中实现向导。 我有一个想法,但我不知道如何实施。 这是我的想法:

我想创建一个component,它将是常见的组件。使用步骤和下一步/后退按钮。喜欢这个

@Component({
    selector: 'div',
    providers: [],
    template: ' <ul class="steps">
        <li *ngFor="#step of steps; #i = index" class="steps-item">
            <a href="#" class="steps-link" [attr.value]="step.value">{{step.name}}</a>
        </li>
    </ul>
    <form >
        <template></template>
        <div>
            <button type="button">Back</button>
            <button type="submit">Submit</button>
        </div>
    </form>',
    pipes: [TranslatePipe],
    directives: []
})

export class WizardComponent {
    steps: any;

    constructor() {
        this.steps = [
            {'name': 'step 1', 'value': '1'},
            {'name': 'step 2', 'value': '2'},
            {'name': 'step 3', 'value': '3'}
        ];
    }
}

然后每个组件将从WizardComponent扩展,以重用所有HTMl和next / back函数。这样的事情。

任何解决方案,谢谢。

1 个答案:

答案 0 :(得分:12)

帮助使用` ngFor

添加组件
export class DclWrapper {
  @ViewChild('target', {read: ViewContainerRef}) target;
  @Input() type;
  cmpRef:ComponentRef;
  private isViewInitialized:boolean = false;

  constructor(private dcl:DynamicComponentLoader) {}

  updateComponent() {
    // should be executed every time `type` changes but not before `ngAfterViewInit()` was called 
    // to have `target` initialized
    if(!this.isViewInitialized) {
      return;
    }
    if(this.cmpRef) {
      throw 'currently changing type after the component was added is not supported'
    }
    this.dcl.loadNextToLocation(this.type, this.target).then((cmpRef) => {
      this.cmpRef = cmpRef;
    });
  }

  ngOnChanges() {
    this.updateComponent();
  }

  ngAfterViewInit() {
    this.isViewInitialized = true;
    this.updateComponent();  
  }
}

您的向导组件使用DclWrapper组件

@Component({
    selector: 'my-wiz',
    providers: [],
    template: ' <ul class="steps">
        <li *ngFor="#step of steps; #i = index" class="steps-item">
          <dcl-wrapper [type]="step"></dcl-wrapper>  
        </li>
    </ul>
    <form >
        <template></template>
        <div>
            <button type="button">Back</button>
            <button type="submit">Submit</button>
        </div>
    </form>',
    pipes: [TranslatePipe],
    directives: [DclWrapper]
})
export class WizardComponent {
    @Input() steps;

    constructor() {}
}

每个步骤的一些示例组件

@Component({
  selector: 'step1',
  template: `<h2>step1</h2>`

})
export class Step1 {
}

@Component({
  selector: 'step2',
  template: `<h2>step2</h2>`

})
export class Step2 {
}

@Component({
  selector: 'step3',
  template: `<h2>step3</h2>`

})
export class Step3 {
}

一起使用

@Component({
  selector: 'my-app',
  directives: [Tabs]
  template: `
  <h2>Hello {{name}}</h2>
  <my-wiz [steps]="steps"></my-tabs>
`
})
export class App {
  Steps = [Step1, Step2, Step3];
}

类似的用例(使用Plunker示例)Angular 2 dynamic tabs with user-click chosen components