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:
<component-a #componentA></component-a>
<component-b [origin]="reference"></component-b>
@ViewChild('componentA', {read: ElementRef}) reference: ElementRef;
@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.
答案 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
设为可观察。