3

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.

Kim Kern
  • 54,283
  • 17
  • 197
  • 195
Daskus
  • 929
  • 1
  • 10
  • 25
  • You can also add `constructor(public elRef: ElementRef)` to `component-a` and pass it like `componentA.elRef`. Within template the template reference variable `#componentA` will always refer to component instance in your case – yurzui Oct 12 '17 at 10:02
  • The thing is I would like to be able to do this with any component. With your solution I would need to override all components and add ElementRef to the contructor – Daskus Oct 12 '17 at 10:08
  • Why do you need to pass whole component to another component as a parameter? – omeralper Oct 12 '17 at 14:26
  • @omeralper I need to clone the native element, do some changes and display it inside the other component – Daskus Oct 12 '17 at 14:33

1 Answers1

0

You can write the service class which can refer to the component and inject the service wherever you require to use the referred component.

@Component
class Component1 implements OnInit{

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

   }

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

ShareService {

   public sharedComponent;

}

Better design would be to have sharedComponent as Observable.

Sunil Singh
  • 11,001
  • 2
  • 27
  • 48