Home > database >  Angular - directive with input with or without value
Angular - directive with input with or without value

Time:06-17

I'm refactoring a directive which adds some sort of a tooltip over the form controls on mouse hover/focus. It's simple to use. Just add it to the element and define its text. The input you use for the text also defines the tooltip's styling

<!-- Creates red tooltip -->
<input matInput type="text" libMessage [libError]="'Error Text'" />
<!-- Creates blue tooltip -->
<input matInput type="text" libMessage [libInfo]="'Info Text'" />
<!-- Creates yellow tooltip -->
<input matInput type="text" libMessage [libWarning]="'Warning Text'" />

We received a request to extend it with option to display not just the text, but also a custom component, which provides better options for styling. It works but it feels bit cumbersome. Instead of just providing a component you have to specify it's type by providing [libError] value with non-empty string.

<!-- Creates red tooltip from simple text -->
<input matInput type="text" libMessage [libError]="'Error Text'" />

<!-- Creates a tooltip from component with red background. Text is ignored. -->
<input matInput type="text" libMessage [libError]="'Error Text'" [libCustomComponent]="someComponent" />

I came with couple of workarounds but was wondering if it's possible to have a directive's input working in two ways. As the Input and the Attribute at the same time. If used with value, it defines the text, if used alone, it defines style but the component has to be provided. Something like this.

<!-- [libError] specifies the text and type -->
<input matInput type="text" libMessage [libError]="'Error Text'" />

<!-- libError defines just a style, no value is needed. -->
<input matInput type="text" libMessage libError [libCustomComponent]="someComponent" />

Is it possible to do something like this?

CodePudding user response:

Yes, it is possible, but then you need to turn your libError property into a boolean instead. For a better overview, check out boolean property coercion (this is how the CDK does it).

For an usage example, we can take a look at the mat-divider. It uses boolean coercion to allow us to write something as simple as this:

<mat-divider vertical />

whenever we need a vertical divider.

CodePudding user response:

I think you can achieve this with the directive that can accept a value using @Input and provide some default value for @Input decorator. So once you provide an input value while adding directive to you DOM element it accept and behave with the input value otherwise if value is not provided directive uses default value that you have set for @Input.

  • Related