使用ng-content Angular的父组件时子组件的辅助功能父组件

时间:2017-02-19 13:53:38

标签: angular angular-components angular2-ngcontent

我尝试使用依赖注入从子组件访问父组件。它可以工作,我可以访问父级使用它的方法和属性,但我没有在Angular doc上看到这种方法。那你对这种方法有什么想法吗?我应该用吗?

因为父组件使用ng-content(比如transclude angularjs)所以我无法使用EventEmitter @Output方法。

下面是我的代码:

wizard.component.ts(parent)

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() { }
}

step.component.ts(child)

<wizard>
    <step>1</step>
    <step>2</step>
    <step>3</step>
</wizard>

app.component.html(主应用)

{{1}}

期待听到您的意见。谢谢!

4 个答案:

答案 0 :(得分:1)

父组件 - &gt;向导组件

@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 - &gt;子组件

@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

答案 1 :(得分:0)

最后,我在https://angular.io/docs/ts/latest/cookbook/dependency-injection.html#!#known-parent找到了关于父依赖注入的文档。

还有一篇文章使用它:https://blog.thoughtram.io/angular/2015/04/09/developing-a-tabs-component-in-angular-2.html

希望它能帮助像我这样有同样担忧的人。

答案 2 :(得分:0)

您可以通过在使用查询列表的父对象上创建一个属性来提供父级和子级通信。您还必须在子组件上添加属性或方法以接收父指针。

@ContentChildren( OptionComponent )
public Options: QueryList<OptionComponent>;

这将为您提供指向父对象中所有子代的指针。这些可以是预计的条目(ngContent)或直接的html声明。然后查询列表将为您获取指向每个孩子的指针。

然后在您的父对象中

public ngAfterViewInit(): void
{
    this.Options.forEach( ( item ) =>
    {
        item.Parent = this;
    } ) 
}

总体简化了,但我认为这提供了基本思想。

答案 3 :(得分:0)

相关问题