我是angular2的新手2,这就是为什么我需要帮助我正在创建多步骤形式,我需要从另一个组件调用方法我在此组件模板中有sallcomponent,我有
<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?感谢您的帮助
找到解决方案。感谢0x2d9a3
我们可以通过在SellComponent: @ViewChild(WizardComponent) wizard;
上声明属性,然后通过访问wizard.stepChange.
WizardComponent
。