首页 > 解决方案 > 角。使用 @viewchild 将 templateRef 与服务一起传递

问题描述

我想知道我是否可以在兄弟之间传递 templateRef 与服务。

简单的例子:

孩子1

export class Child1 implements OnInit {

@ViewChild('button', {static: true})
    private buttonTpl: TemplateRef<any>;
    
constructor(private service: ParentService) {}
    
 //some click method here 
  
ngOnInit() {
  this.service.button = this.buttonTpl;
}
<ng-template #button>
  <button some click method >Click</button>
</ng-template>

孩子2

export class Child2 implements OnInit {

button;

constructor(private service: ParentService){}

ngOnInit {
  this.button = this.service.button;
}
Child2 template:

I would like to show button here (as in toolbar) but have the functionality below.
<ng-container *ngTemplateOutlet='button'></ng-container>

Child1 content is routed here 
<ng-content select='.router-outlet'>

这是我在父级别创建的服务,孩子应该可以访问

export class ParentService {
  button: TemplateRef<any>;
}

当我在父组件中有我的 ng-template #button 和 viewChild 时,该服务运行良好,我能够将按钮呈现给 Child2。但是现在当试图在兄弟姐妹之间传递时,这是行不通的。甚至可以使用这种方法还是我应该尝试其他方法?

编辑:父 html 示例

<div>
  <child2>
    <router-outlet class='router-outlet'>
    //this contains child1
    </router-outlet>
  </child2>
</div>

标签: angular

解决方案


推荐阅读