簡體   English   中英

如何在沒有ViewChild的情況下將模板變量傳遞給組件

[英]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;

成分B

 @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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM