Building our own Custom Directive

Building our own Custom Directive

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>

Logic behind creating custom directive

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.

app.module.ts code

Now we can use our directive anywhere in the components to change the view as per our requirements.

Using true/false values to render the view.

Here’s the output of the code:

The output of using the custom directive.



Vijay Sadashive

Lead Software Engineer @Persistent | Developer | JavaScript |

3 年

Great??

回复

要查看或添加评论,请登录

社区洞察

其他会员也浏览了