[英]How to pass template variable to component without ViewChild
我需要将一个组件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;
有没有一种方法可以让它在没有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
为Observable。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.