【发布时间】:2017-07-08 18:10:53
【问题描述】:
我正在尝试使用依赖注入从子组件访问父组件。它有效,我可以访问父级以使用它的方法和属性,但我没有在 Angular 文档上看到这种方法。那么你对这种方法有什么想法吗?我应该使用它吗?
因为父组件使用 ng-content(比如 transclude angularjs)所以我不能使用 EventEmitter @Output 方法。
下面是我的代码:
wizard.component.ts(父级)
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'wizard',
template: `
<div>
<ng-content></ng-content>
<button>Back</button>
<button>Next</button>
</div>
`
})
export class WizardComponent implements OnInit {
steps = [];
constructor() { }
addStep(step) {
this.steps.push(step);
}
ngOnInit() { }
}
step.component.ts(子)
import { WizardComponent } from './wizard.component';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'step',
template: `
<div>Step <ng-content></ng-content></div>
`
})
export class StepComponent implements OnInit {
constructor(private parent: WizardComponent) {
this.parent.addStep(this);
}
ngOnInit() { }
}
app.component.html(主应用)
<wizard>
<step>1</step>
<step>2</step>
<step>3</step>
</wizard>
期待听到您的意见。谢谢!
【问题讨论】:
-
你在所有地方都用
<ng-content>弄乱了组件。你能分享你想要实现的图像布局吗? -
应该是一个普通的向导,有很多步骤,然后我们可以下一步,后退一步。在每一步中,我们都有不同的 html 设计,这就是我使用 ng-content 的原因。抱歉,我没有布局图像,我正在处理它。谢谢
-
如果您能详细说明您的问题,我可以帮助您吗
-
我担心我可以从子组件中注入父组件,例如 Angular 中的注入服务,但我在 Angular 文档上没有看到这种方法。所以不知道是好是坏?
-
对不起,我不是。我用的是手机。顺便说一句,非常感谢您的 cmets ;)
标签: angular angular-components angular2-ngcontent