0

我正在嘗試動態注入角度爲4的組件。 我成功地能夠做到這一點,但是我遇到的問題是當我試圖綁定它變成一個目標ViewChild在templateUrl中未定義,但不是模板

<div> 
    <ng-template #detailedGrid></ng-template>  
</div> 

當我在我的代碼呈現時,我不斷收到一個錯誤,我的目標沒有定義。

這裏是縮小代碼:

@Component({  
    templateUrl: '../../common/components/grid/templates/grid.html' 
    //template: `<div #detailedGrid></div>` 
}) 
export class ListComponent implements OnInit, AfterViewInit { 
    @ViewChild('detailedGrid', {read: ViewContainerRef}) target: ViewContainerRef; 

constructor(private componentFactoryResolver: ComponentFactoryResolver, 
      private viewContainerRef: ViewContainerRef) {} 

ngAfterViewInit() { 

const factory = this.componentFactoryResolver.resolveComponentFactory(DetailedListComponent); 
     const ref = this.viewContainerRef.createComponent(factory); // <-- this one works 
     // const ref = this.target.createComponent(factory); // <-- This one does not work 
     ref.changeDetectorRef.detectChanges(); 
} 

的作品基本上只是在頁面底部添加的那個。我所想要做的就是把它注射到DIV位置

錯誤:

Cannot read property 'createComponent' of undefined

「目標」永遠不會被定義。

所以有趣的是,當我將代碼放入模板內,目標代碼工作,但是當它位於templateUrl html代碼中時,它不會。

更新:所以我想通了這個問題只是沒有解決

的問題是,我的HTML標籤是另一個組件的標籤中

代碼是HTML裏面在此組件

<grid></grid> 

當我在網格組件的外部帶出div標籤時,它工作。 所以我的問題是如何在網格組件中訪問它。

+0

請發帖喲你完整的模板..它主要發生在元素被封閉在* ngifs內 –

回答

0

好了,所以該解決方案是向上移動

@ViewChild('detailedGrid', {read: ViewContainerRef}) 
public detailedGrid: ViewContainerRef; 

到GridComponent

然後引用該網格成分作爲

@ViewChild(GridPageComponent) gridPageComponent: GridPageComponent; 

現在我可以訪問目標

const factory = this.componentFactoryResolver.resolveComponentFactory(PatientsDetailedListComponent);    
const ref = this.gridPageComponent.detailedGrid.createComponent(factory); 
ref.changeDetectorRef.detectChanges();