如何从另一个组件angular2调用方法

时间:2016-12-21 19:35:12

标签: angular typescript

我是angular2的新手,这就是我需要帮助的原因 我正在创建多步形式,我需要从另一个组件调用方法 我在这个组件模板中有SellComponent

<sell-wizard>
  <sell-wizard-step></sell-wizard-step>
</sell-wizard>

我必须调用位于WizardComponent中的方法 以下来自组件的代码

WizardComponent

import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'sell-wizard',
template: "
<ng-content></ng-content>
<div
  class="my-wizard__footer">
  <button
    [style.visibility]="isOnFirstStep() ? 'hidden' : 'visible'"
    (click)="stepChange.emit(step - 1)">
    Previous
  </button>
  {{step}} / {{steps}}
  <button
    *ngIf="!isOnFinalStep()"
    (click)="stepChange.emit(step + 1)">
    Next
  </button>
  <button
    *ngIf="isOnFinalStep()"
    (click)="finish.emit(step + 1)">
    {{finishText}}
  </button>
</div>",
})
export class WizardComponent {
@Input() finishText = 'Finish';
@Input() step = 1;
@Output() finish = new EventEmitter();
@Output() stepChange = new EventEmitter();
private steps = 0;
private isOnFinalStep = () => this.step === this.steps;
private isOnFirstStep = () => this.step === 1;

public addStep() {
  const newSteps = this.steps + 1;
  this.steps = newSteps;
  return newSteps;
}}

WizardStepComponent

import { Component, Input } from '@angular/core';
import { WizardComponent } from './wizard.component';

@Component({
  selector: 'sell-wizard-step',
  host: {
    '[style.display]': 'isCurrent ? "block" : "none"',
  },
  template: `<ng-content></ng-content>`,
})
export class WizardStepComponent {
private isCurrent;
private step;

constructor(
  private parent:WizardComponent
  ) {}

ngOnInit() {
  this.step = this.parent.addStep();

  this.isCurrent = this.step === this.parent.step;

  this.parent.stepChange.subscribe(step => {
    this.isCurrent = this.step === step;
  });
 }
}

SellComponent

import { Component, Input} from '@angular/core';


@Component({
  moduleId: module.id,
  selector: 'sell',
  templateUrl: 'sell.component.html'
})
export class SellComponent  {
  private step = 1;

  constructor(){}
}

所以在这个SellComponent视图中,我试图从WizardComponent调用方法

<button type="button" (click)="stepChange.emit(step + 1)">next</button>

它说Cannot read property 'stepChange' of undefined 我如何从另一个组件调用fucntion? 谢谢你的帮助

1 个答案:

答案 0 :(得分:0)

找到解决方案。感谢0x2D9A3

我们可以通过在WizardComponent上声明属性来访问我们的SellComponent中的SellComponent: @ViewChild(WizardComponent) wizard;,然后通过访问wizard.stepChange.

来发出事件
相关问题