It's a classic - so let's stick with it, and let's declare and build a
HelloWorldDirective together. Follow along as we create a new attribute directive using Stackblitz, a powerful online editor.
Using Stackblitz you can easily create an Angular project, as well as generate out directives. The generated directives are already declared for you in the closest module
Don't get too caught up in the details here. We're going to cover everything together in the future.
To start with, we'll inject the
ElementRef class instance using Angular's powerful dependency injection system. To get access to the
ElementRef, we simply specify a class member property via the class's
constructor function using the accessor anotation (either
protected) along with the type. In this example, the type is
ElementRef. This type is an injection token by which the Angular compiler can determine the appropriate class instance to inject.
We'll also implement an interface, or code contract, that uses a lifecycle hook method. Angular provides several "special" methods that can be declared in you directive class that will be invoked during specific steps in the lifecycle of a directive, from be initialized to being destroyed. In our example, we'll be using the
ngOnInit() lifecycle method that is required by the
Finally, we'll access the
nativeElement property on the
ElementRef instance that is injected into our directive. Using this property we have access to the element in the Document Object Model (DOM). In our example, the element that we are applying the directive to is an
HTMLParagraphElement, which has an
innerHTML property that we can set to a string. Setting that value modifies the element and we instantly see that the element's content is updated.