Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4: How to access element inside ng-template

Tags:

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.

like image 900
Senthil Raj Avatar asked Oct 26 '17 09:10

Senthil Raj


1 Answers

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>;
like image 163
Huantao Avatar answered Sep 20 '22 14:09

Huantao