How to pass template variable to component without ViewChild

时间:2017-10-12 10:00:13

标签: javascript angular viewchild

I need to pass a component A to another component B. Component B needs access to the nativeElement of A. I managed to get it to work like this:

Container

Template

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

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

Controller

@ViewChild('componentA', {read: ElementRef}) reference: ElementRef;

Component B

 @Input() origin: ElementRef;

Is there a way to get it to work without ViewChild, just with passing the template reference?

It should look like this:

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

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

Right now if I do it like this I cannot access the nativeElement.

1 个答案:

答案 0 :(得分:0)

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

@Component
class Component1 implements OnInit{

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

   }

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

ShareService {

   public sharedComponent;

}

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