Angular 2:从嵌套的子组件调用root组件的方法

时间:2016-09-21 08:59:03

标签: angularjs angular typescript angular-cli

我的应用程序中有很少的组件:

//.ts:

RootComponent
-ParentComponent
--ChildComponent
---LastLevelComponent


//.html

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

我想从LastLevelComponent调用Rootcomponent的方法。

  

了解EventEmitter,但问题是我需要通过   每个子组件的值。   有什么方法我可以直接打电话   没有的LastLevelComponent的RootComponent方法   依赖于ParentComponent或ChildComponent。

2 个答案:

答案 0 :(得分:0)

您可以在@Input()中使用LastLevelComponent。 或者没有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>

答案 1 :(得分:0)

您可以通过创建服务来解决此问题。请按照以下步骤操作:

  1. 创建服务
  2. @Injectable() 导出类CompService {

    private componentRef = null;
    
    constructor(){
    }
    
    getParent(){
        return this.componentRef;
    }
    
    setParent(ref){
        this.componentRef = ref;
    }
    

    }

    1. 在根组件的“供应商”部分中包含此服务:
    2. @Component({     。 。

      providers: [CompService]
      

      }) 导出类RootComponent {

      constructor(
          private cmpService?: CompService)
      {
      }   
      

      }

      1. 在根组件初始化期间,调用服务以将组件值设置为指向根:

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

      2. 在子组件或最后一级组件中,调用此服务以检索根组件:

      3. @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();
           }
        }
        

        }

        您可能会注意到CompService仅在 设置在根组件的providers部分中。这使得能够拥有该服务的一个实例。因此,所有子组件都将继承指向根组件的服务设置。

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

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