Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@ViewChildren(TemplateRef) is undefined for <template> elements

Tags:

angular

How can I get a collection of all templates (TemplateRef) inside a component? It works fine with ViewChild but ViewChildren is undefined...

I use a solution from this question. Plunker with the full example.

  @Component({
    selector: 'my-app',
    template: `
            <div>
              <template #model>...</template>
              <template #color>...</template>
            </div>`
  })
  export class App {
  @ViewChild('model') model;
  @ViewChild('color') color;
  @ViewChildren(TemplateRef) templates: QueryList<TemplateRef>;

  ngAfterContentInit() {
    console.log(this.templates); // undefined
    console.log(this.model); // TemplateRef_ {...}
  }
}

I need templates for a grid component where it's possible to define templates for columns. Unfortunately ng-content doesn't support dynamic projection, so I'm trying to achieve it with templates.

like image 353
Ievgen Martynov Avatar asked Mar 31 '17 16:03

Ievgen Martynov


People also ask

How to access the elements from the templateref?

You can't directly access the elements from the templateRef. You need to follow the same process using @ViewChildren. The elementRef that is available on the templateRef as shown here just points to the DOM host element that Angular created for the template element - it's a comment node.

What is @viewchildren decorator in angular?

Angular @ViewChildren. Angular @ViewChildren Decorator is used to get the QueryList of elements or directives from the view DOM. When a new child element is added or removed, the QueryList will be updated and its changes function will emit new value. @ViewChildren sets the data before ngAfterViewInit callback.

What is the difference between an elementref and a viewchild?

ViewChild returns a ElementRef, which is nothing but a wrapper around the native HTML element. There could be multiple instances of the same component or element in the Template. The ViewChild always returns the first component.

What is the difference between ngafterviewinit and @viewchildren?

When a new child element is added or removed, the QueryList will be updated and its changes function will emit new value. @ViewChildren sets the data before ngAfterViewInit callback.


1 Answers

If you move console.log('child', this.templates); to ngAfterViewInit() then it works.

ngAfterViewInit() {
  console.log('child', this.templates);
}

I had expected it to work in ngAfterContentInit() as well. It seems in this Angular version ngAfterContentInit() runs before ngAfterViewInit(). I was sure this was the other way around earlier.

Plunker example

like image 71
Günter Zöchbauer Avatar answered Oct 19 '22 20:10

Günter Zöchbauer