5

I have a view which holds ng template for MD-Dialog.

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

Where I have to replace #content with a dynamic component.

corresponding component class is,

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

But I get undefined for this.container in method open(). Please help.

5
  • can you create a stackblitz demo? Commented Oct 26, 2017 at 9:08
  • demo is little difficult at the moment. let me shorten the problem, i want to access #content in the method open(). since it is in ng-template, im not able to access it. Commented Oct 26, 2017 at 9:39
  • so create a minimal demo Commented Oct 26, 2017 at 9:45
  • angular-ukdpqg.stackblitz.io here is the demo and code is here stackblitz.com/edit/angular-ukdpqg Commented Oct 26, 2017 at 10:03
  • What are you trying to achieve? @ViewChild('content') will be available only after creation embedded view Commented Oct 26, 2017 at 11:04

1 Answer 1

4

template inside a template is reachable only when view is initialized, so after angular 8, when using ViewChild, you can use parameter{static: false} this way you can have instance of the inside template when view is initialized

@Viewchild('content', {static: false}) innerConttent: TemplateRef<any>;
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.