Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access @ViewChild template from ng-content

Tags:

angular

Is it possible to use templates in combination with ng-content like described here:

app component:

<table-column>
  <template #template let-item="item">
    <input type="text" [(ngModel)]="item.foo" />
  </template>
</table-column>

table-column component:

@Component({
  selector: 'table-column',
  template: '<ng-content></ng-content>'
})
export class TableColumnComponent implements OnInit {
  @ViewChild('template') template;  

  ngOnInit() {
    console.log(this.template); // undefined
    // create column object with template and different metadata...
  });      
}

Plunker?

The problem I get undefined using different life cycle hooks (ngOnInit, ngAfterViewInit)...

like image 720
Ievgen Martynov Avatar asked Apr 03 '17 14:04

Ievgen Martynov


People also ask

What is the difference between Ng-content ng container and ng template?

ng-container serves as a container for elements which can also accept structural directives but is not rendered to the DOM, while ng-template allows you to create template content that is not rendered until you specifically (conditionally or directly) add it to the DOM.

What is the difference between ViewChild () and ContentChild ()?

ViewChild is used to select an element from component's template while ContentChild is used to select projected content.

How do you use NG-content?

The ng-content is used when we want to insert the content dynamically inside the component that helps to increase component reusability. Using ng-content we can pass content inside the component selector and when angular parses that content that appears at the place of ng-content.

What is ContentChild and ContentChildren?

The ContentChild & ContentChildren are decorators, which we use to Query and get the reference to the Projected Content in the DOM. Projected content is the content that this component receives from a parent component. The ContentChild & ContentChildren is very similar to the ViewChild & ViewChildren.


1 Answers

If you want to search within Light DOM then you need to use @ContentChild and wait until ngAfterContentInit hook

@ContentChild('template') template;  

ngAfterContentInit() {
  console.log(this.template);
}

See also

  • What's the difference between @ViewChild and @ContentChild?
like image 188
yurzui Avatar answered Oct 12 '22 03:10

yurzui