我正在尝试使用依赖注入(inject)从子组件访问父组件。它有效,我可以访问父级以使用它的方法和属性,但我没有在 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>
期待听到您的意见。谢谢!
最佳答案
父组件->向导组件
@Component({
selector: 'wizard',
template: `
<div>
<steps [steps]="steps"> </steps>
<button> Back </button>
<button> Next </button>
<button (click)="addStep()"> Add a step </button>
</div>
`,
})
export class WizardComponent {
steps:any[]=new Array();
constructor() {
this.steps.push({id:1,name:'abc'});
this.steps.push({id:2,name:'abc'});
this.steps.push({id:3,name:'abc'});
}
addStep(){
let count = parseInt(this.steps.count) + 1;
this.steps.push({id:count,name:'abc'});
}
}
StepComponent -> 子组件
@Component({
selector: 'steps',
template: `
<div>
<span *ngFor="let step of steps">
<label> {{step.id}} </label>
<div> {{step.name}} </div>
</span>
</div>
`,
})
export class StepsComponent {
@Input() steps:any[]=new Array();
constructor() {
}
}
更新 1:每个步骤中都会出现不同的元素,所以我建议你使用
<ng-content>
如下<div>
<ng-content select=".step-body"> </ng-content>
</div>
你的向导看起来像
<table>
<tr>
<td>
<steps>
<div class="step-body">
hi hello
</div>
</steps>
</td>
<td>
<steps>
<div class="step-body">
something else
</div>
</steps>
</td>
</tr>
</table>
LIVE DEMO
关于angular - 当父组件使用 ng-content Angular 时从子组件访问父组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42328048/