DEV Community

Discussion on: Angular Templates — From Start to Source

Collapse
 
crutchcorn profile image
Corbin Crutchley

The example you linked was not only broken as you pointed out, but the code inside the StackBlitz was outdated compared to the code in the article. It has now been updated to reflect the article properly.

To explain why:

    <div>
      Hello There!
      <ng-template #testingMessage><p>Testing 123</p></ng-template>
    </div>
    <ng-template [ngTemplateOutlet]="testingMessage"></ng-template>
Enter fullscreen mode Exit fullscreen mode

Renders the test message but:

    <ng-template #helloThereMsg>
      <p>Hello There!</p>
      <ng-template #testingMessage>
        <p>Testing 123</p>
      </ng-template>
    </ng-template>
    <div>
      <ng-template [ngTemplateOutlet]="helloThereMsg"></ng-template>
    </div>
    <ng-template [ngTemplateOutlet]="testingMessage"></ng-template>
Enter fullscreen mode Exit fullscreen mode

Does not is because of the parent scoping.

Inside of the helloThereMsg, there is a new scope. Because of this, you cannot access testingMessage outside of that scope, which is why it doesn't render. However, a div does not create a new template scope, and therefore it does render.

This is similar to the following javascript code:

const testingMessage = "Testing 123";

console.log(testingMessage);
Enter fullscreen mode Exit fullscreen mode

This runs just fine

vs.

{
const testingMessage = "Testing 123";
}
console.log(testingMessage);
Enter fullscreen mode Exit fullscreen mode

This will throw an error because testingMessage is not in scope anymore and does not hoist due to const

Collapse
 
hassam7 profile image
Hassam Ali

thanks for the clarification.

Your article is very in depth and thorough. I was always confused by Host View and Embeded View but after the article it made sense. I am sure I have missed some stuff I will be reading it again and bookmarking it.