2016-09-21 57 views
0

调用根组件的方法,我在我的应用程序几个组件:角2:嵌套的子组件

//.ts: 

RootComponent 
-ParentComponent 
--ChildComponent 
---LastLevelComponent 


//.html 

<root-component> 
<parent-component> 
    <child-component> 
    <last-level-component></last-level-component> 
    </child-component> 
</parent-component> 
</root-component> 

我想打电话给Rootcomponent从LastLevelComponent的方法。

我知道EventEmitter,但问题是我需要将 值传递给每个子组件。 有没有什么办法可以直接调用 从LastLevelComponent RootComponent的方法,而不是 依赖于ParentComponent或ChildComponent。

回答

0

您可以在您的LastLevelComponent中使用@Input()。 或者没有Child-和ParentComponent的@Output()需要使用此事件。

//.html 

<root-component #rootCmp> 
<parent-component> 
    <child-component> 
    <last-level-component [root-comp]="rootCmp" (myOutput)"rootCmp.func()"></last-level-component> 
    </child-component> 
</parent-component> 
</root-component> 
0

您可以通过创建服务来解决此问题。遵循以下步骤:

  1. 创建服务

@Injectable() 出口类CompService {

private componentRef = null; 

constructor(){ 
} 

getParent(){ 
    return this.componentRef; 
} 

setParent(ref){ 
    this.componentRef = ref; 
} 

}

  • 包括此服务位于您的根组件的供应商部分中:
  • @Component({ 。 。 。

    providers: [CompService] 
    

    }) 出口类RootComponent {

    constructor(
        private cmpService?: CompService) 
    { 
    } 
    

    }

  • 在根组件的初始化,呼叫设置组件服务值指向根:

    ngOnInit(){ this.cmpService.setParent(this); }

  • 在子组件或最后一级组件,调用此服务来检索根组件:

  • @Component(。{ }) 出口类LastLevelComponent {

    constructor(
        private cmpService?: CompService) 
    { 
    } 
    
    someMethod(){ 
        if (this.cmpService){ 
         let parentCtrl = this.cmpService.getParent(); 
    
         // Call your parent method or property here 
         // if (parentCtrl) 
         // parentCtrl.rootMethod(); 
        } 
    } 
    

    }

    您可能会注意到CompSer副本是只有设置在根组件的提供者部分。这使得有一个这种服务的实例。因此,所有子组件都将继承指向根组件的服务设置。

    您只需调用每个子组件中服务的getParent方法即可访问根组件公共方法,属性和事件。

    此外,该服务是可重用的,并避免任何其他组件的依赖。