Angular ng-template, ng-container and ngTemplateOutlet: Guided Tour (angular-university.io)
One key question about templates is, what is visible inside them?
Does the template have its own separate variable scope, what variables can the template see?
Inside the ng-template tag body, we have access to the same context variables that are visible in the outer template, such as for example the variable lessons
.
And this is because all ng-template instances have access also to the same context on which they are embedded.
But each template can also define its own set of input variables! Actually, each template has associated a context object containing all the template-specific input variables.
Let's have a look at an example:
Here is the breakdown of this example:
- this template, unlike the previous templates also has one input variable (it could also have several)
- the input variable is called
lessonsCounter
, and it's defined via a ng-template property using the prefixlet-
- The variable lessonsCounter is visible inside the ng-template body, but not outside
- the content of this variable is determined by the expression that its assigned to the property
let-lessonsCounter
- That expression is evaluated against a context object, passed to
ngTemplateOutlet
together with the template to instantiate - This context object must then have a property named
estimate
, for any value to be displayed inside the template - the context object is passed to
ngTemplateOutlet
via the context property, that can receive any expression that evaluates to an object
Given the example above, this is what would get rendered to the screen:
Approximately 10 lessons ...
This gives us a good overview of how to define and instantiate our own templates.
Another thing that we can also do is interact with a template programmatically at the level of the component itself: let's see how we can do that.
Template References
The same way that we can refer to the loading template using a template reference, we can also have a template injected directly into our component using the ViewChild
decorator:
As we can see, the template can be injected just like any other DOM element or component, by providing the template reference name defaultTabButtons
to the ViewChild
decorator.
This means that templates are accessible also at the level of the component class, and we can do things such as for example pass them to child components!
An example of why we would want to do that is to create a more customizable component, where can pass to it not only a configuration parameter or configuration object: we can also pass a template as an input parameter.
Không có nhận xét nào:
Đăng nhận xét