Javascript 如何在没有ViewChild的情况下将模板变量传递给组件

Javascript 如何在没有ViewChild的情况下将模板变量传递给组件,javascript,angular,viewchild,Javascript,Angular,Viewchild,我需要将一个组件a传递给另一个组件B。 组件B需要访问A的nativeElement。 我设法让它像这样工作: <component-a #componentA></component-a> <component-b [origin]="componentA"></component-b> 容器 模板 B部分 是否有一种方法可以让它在不使用ViewChild的情况下工作,只需传递模板引用? 应该是这样的: <component-a #c

我需要将一个组件a传递给另一个组件B。 组件B需要访问A的nativeElement。 我设法让它像这样工作:

<component-a #componentA></component-a>

<component-b [origin]="componentA"></component-b>
容器 模板 B部分
是否有一种方法可以让它在不使用ViewChild的情况下工作,只需传递模板引用?

应该是这样的:

<component-a #componentA></component-a>

<component-b [origin]="componentA"></component-b>


现在,如果我这样做,我就无法访问nativeElement。

您可以编写服务类,该类可以引用组件,并在需要使用引用组件的任何地方注入服务

@Component
class Component1 implements OnInit{

   constructor(private ShareService : ShareService, private ref : ElementRef){

   }

   public ngOnInit(){
       this.shareService.sharedComponent = this.ref;
   }
}

ShareService {

   public sharedComponent;

}

更好的设计是将
sharedComponent
作为可观察的组件。

您还可以将
构造函数(public elRef:ElementRef)
添加到
组件-a
中,并像
组件a.elRef
一样传递它。在模板中,模板引用变量
#componentA
将始终引用组件实例。在您的案例中,我希望能够对任何组件执行此操作。使用您的解决方案,我需要覆盖所有组件并将ElementRef添加到构造函数中。为什么需要将整个组件作为参数传递给另一个组件?@omeralper我需要克隆本机元素,进行一些更改,并将其显示在另一个组件中
<component-a #componentA></component-a>

<component-b [origin]="componentA"></component-b>
@Component
class Component1 implements OnInit{

   constructor(private ShareService : ShareService, private ref : ElementRef){

   }

   public ngOnInit(){
       this.shareService.sharedComponent = this.ref;
   }
}

ShareService {

   public sharedComponent;

}