2017-10-26 11 views
0

私はMD-Dialogのテンプレートを保持するビューを持っています。角4:ng-template内の要素にアクセスする方法

<ng-template #template> 
    <h2 md-dialog-title>{{title}}</h2> 
    <div md-dialog-content #content></div> 
</ng-template> 

ここで#contentを動的コンポーネントに置き換える必要があります。

対応するコンポーネントクラスが

export class CustomDialogComponent implements OnInit, AfterViewInit { 

    title: string; 

    @ViewChild('content', { read: ViewContainerRef }) container; 

    @ViewChild('template') template: TemplateRef<any>; 

    constructor(public dialog: MdDialog, 
    private componentFactoryResolver: ComponentFactoryResolver) { } 

    ngOnInit() { 
    } 

    open(component: any, options: any): void { 

    this.title = options.title; 
    console.log(this.container) 
    const dialogRef = this.dialog.open(this.template, options); 
    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(component); 
    this.container.clear(); 
    const comp = this.container.createComponent(componentFactory); 
    comp.instance.setData(options.data); 

    } 

    close() { 
    this.dialog.closeAll(); 
    } 

    ngAfterViewInit() { 
    console.log(this.container) 
    } 
} 

、あるしかし、私はこの方法でthis.containerオープン未定義の取得()。助けてください。

+0

あなたはstackblitzデモを作成することができますか? –

+0

デモは現時点ではほとんど難しくありません。問題を短くして、open()メソッドで#contentにアクセスしたい。 ng-templateに入っているため、アクセスできません。 –

+0

最小デモを作成 –

答えて

0

あなたの代わりにNG-テンプレートのコンテナngを試すことができます。

<ng-container> </ng-container>

関連する問題