Building our own Custom Directive
Divanshi Kumawat
Angular | Node.js | UI developer | Frontend developer | javaScript | MEAN Stack
Who hasn’t heard of the famous structural directive ngIf? We all use it for various purposes. We might want to render a component on a click of a button, or want to show a loading page while waiting for the data to load. There are 'n' number of use cases for ngIf.
But let’s just imagine our lives without this directive, what would we have done then? Or let’s just say that your design construct is such that you cannot use these built-in directives. How are we supposed to brainstorm our way through it?
We can make our own custom directives. Here’s how:
You can create your own directive with this command: ng g directive <name>
Directive: These are classes that add additional behavior to elements in our?Angular?applications. The?@Directive()?decorator's configuration property specifies the directive's CSS attribute selector, in this case [‘myNgIfNot’].
Input Decorator: It is used to communicate between the two components. It sends data from parent to child using property binding
TemplateRef: It helps us to use data from one part of a template in another part of the template. With template variables, we instantiate the embedded views linked to the template which is to be rendered.
ViewContainerRef: Represents a container where one or more views can be attached to a component. We can use?createEmbeddedView ()?function to attach the embedded templates in the container.
For our directive to work, we need to import it in our app.module.ts file.
Now we can use our directive anywhere in the components to change the view as per our requirements.
Here’s the output of the code:
Lead Software Engineer @Persistent | Developer | JavaScript |
3 年Great??