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(); 
} 

だけで、本質的に働く1ページの一番下に追加されます。ここでは

は縮小コードがあります。

Cannot read property 'createComponent' of undefined

「ターゲット」に定義されることは決してありません:私は何をしたいと思っていますして

エラーのdivの場所に注入されます。

興味深いことに、私はテンプレートの中にコードを置くと、ターゲットコードは動作しますが、templateUrl htmlコードの中にあるときはそうではありません。

更新:だから私はこの問題だけではない解決策の問題は、HTMLでの私のタグが

コードは、このコンポーネントのHTML内の別のコンポーネントのタグ内にされていることである

を考え出し

<grid></grid> 

グリッドコンポーネントの外側にdivタグを持ってきたときに働いていました。 私の質問はどのようにグリッドコンポーネント内でそれにアクセスするのですか?

+0

投稿してください全体のテンプレート。これは主に要素が* ngifs内に囲まれている場合に発生します –

答えて

0

オクラホマので、解決策は今、ターゲットにアクセスすることができる

は次に

@ViewChild(GridPageComponent) gridPageComponent: GridPageComponent; 

としてグリッド・コンポーネントを参照GridComponentにアップ

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

を移動させることである

const factory = this.componentFactoryResolver.resolveComponentFactory(PatientsDetailedListComponent);    
const ref = this.gridPageComponent.detailedGrid.createComponent(factory); 
ref.changeDetectorRef.detectChanges(); 
関連する問題