In my last blog article I wrote an introduction to structural directives. This blogpost builds upon the knowledge we learned there.
In a structural directive we can receive content in order to use it in our projected template.
<div *appFoo="let bar">{{bar}}</div>
The structural directive would provide the context and by using $implicit
the content becomes available. In this case it is a hard coded string ‘Hello World’.
@Directive({selector: 'appFoo'})
export class FooDirective implements OnInit {
constructor(private viewContainer: ViewContainerRef,
private templateRef: TemplateRef<{$implicit: string}>{ }
ngOnInit(){
this.viewContainer
.createEmbeddedView(
this.templateRef,
{$implicit: 'Hello World'})
}
}
TemplateRef
is a generic class. The generic type that…
An important part of building scaleable web applications, is creating your own toolbox of re-usable components.
However, building re-usable components is not always easy because they might have to fit different requirements.
The more flexible a component is, the more requirements it can support. Of course, before extending an existing component with new functionality, one has to always think about whether the functionality makes sense for that component or whether it shall rather be a new component for itself. For a better understanding let us have a look at the following example. Product management is asking us to replace the…
A structural directive is defined like any other directive but with one major difference: In the constructor TemplateRef
and/or ViewContainerRef
is injected.
TemplateRef
allows to access the projected DOM content of the element where the structural directive is applied on, whereas ViewContainerRef
is the service that allows to render any given templateRef
.
As soon as TemplateRef
and/or ViewContainerRef
is injected into the constructor the directive becomes a structural directive.
This also changes how the directive is applied on an element: A structural directive can be applied only on ng-templa
elements or the asterix notation has to be used.
You…
I'm a PWA developer with 7+ years of Angular experience. During the day I develop the WebApp for an IOT business application, during the night I work on aux.app