[英]How to pass template variable to component without 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: 我需要将一个组件A传递给另一个组件B。组件B需要访问A的nativeElement。我设法使它像这样工作:
<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? 有没有一种方法可以让它在没有ViewChild的情况下工作,只需传递模板引用即可?
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. 现在,如果我这样做,将无法访问nativeElement。
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. 更好的设计是将
sharedComponent
为Observable。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.