2017-02-19 86 views
0

我試圖從使用依賴注入的子組件訪問父組件。它的工作原理,我可以訪問父母使用它的方法和屬性,但我沒有看到Angular doc上的這種方法。那麼你對這種方法有什麼想法嗎?我應該使用它嗎?當父組件使用ng-content時,子組件的可訪問性父組件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> 

L嘟forward着聽你的意見。謝謝!

+0

你在所有地方都搞糟了''的組件。你能分享你試圖實現的圖像佈局嗎? – Aravind

+0

它應該是一個有很多步驟的普通向導,然後我們可以去下一步,回去一步。並且在每一步中,我們都有不同的html設計,以便我使用ng-content。對不起,我沒有佈局圖像,我正在處理它。謝謝 –

+0

如果你可以詳細說明你的問題,我可以幫你解決 – Aravind

回答

1

家長成分 - >精靈組件

@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

+0

非常感謝你的努力!這是實現我的目標的替代方案,但在每一步我都有不同的html佈局,所以我不能像這樣使用repeat ngFor。不管怎麼說,還是要謝謝你。 –

相關問題