Home > Blockchain >  Angular Content projection with nested children
Angular Content projection with nested children

Time:08-16

enter image description here

CodePudding user response:

I believe that content children might not be the right call. Using ViewChildren results in them being discovered. However, a few modifications need to be made.

Your selector in your directive is set as [customTemplate]. This is fine, however the selectors are case sensitive. Thus in your HTML when you use it as CustomTemplate it won't be discovered. Thus change your HTML to be either customTemplate or update your selector to have a capital C.

Secondly, in order to do anything of value with said ViewChildren, as is mentioned here (@ViewChildren Querylist Array is empty when children are rendered with *ngFor) you need to subscribe to any changes that occur in your AfterViewInit

ex:

this.templates.changes.subscribe((x) => console.log("From Change Sub: ", x));

Lastly, instead of trying to find the children using a string literal, pass in the actual class name instead as so:

@ViewChildren(CustomTemplate) instead of @ViewChildren('CustomTemplate') or @ViewChildren('customTemplate')

The latter two do not work, the first one does. Also with the first one if you ever do decide to change the name of the class it will propagate throughout the app, and anywhere it did not the typechecker will find it.

Updated stackblitz https://stackblitz.com/edit/angular-z5a8ae?file=src/app/app.component.html

  • Related