([])
. Such an approach, although it is most often used by him, is not the only possible one. In fact, selectors used in directives give the programmer a wide scope for creativity. In order to demonstrate this idea in action, the material, the translation of which we publish today, discusses the methodology for creating a directive designed to work with external links that are in the template. In particular, we will discuss how to find ordinary HTML elements, and, if necessary, exclude some of them from the sample, using the :not
pseudo- :not
.ngForm
directive: @Directive({ selector: 'form:not([ngNoForm]):not([formGroup]),ngForm,ng-form,[ngForm]', })
<form>
) with HTML attributes (like ngForm
).:not
pseudo- :not
.<a>
tag, which does not have a routerLink
directive. Considering what we found out by analyzing the previous example, the corresponding selector can be described as follows: @Directive({ selector: 'a:not([routerLink])', })
externalLink
, but this is completely unnecessary, since this approach translates into duplication of already existing mechanisms. It is also easy to forget to add a similar directive to some external links. The strength of our method lies in the fact that, thanks to one line, we can access all external links.rel
attribute to the link, which will improve performance and increase security of the solution.@HostBinding()
: @Directive({ selector: 'a:not([routerLink])' }) export class ExternalLinkDirective { @HostBinding('rel') @Input() rel = 'noopener'; @HostBinding('target') @Input() target = '_blank'; }
@Input()
decorator, which, if necessary, opens up possibilities for redefinition.@Attribute()
decorator. This approach will give a slight increase in performance, since, unlike the @Input()
decorator, when using @Attribute()
values of the corresponding properties are calculated only once, that is, there is no constant checking of the rel
and target
properties in the change check loop. <nav> <a href="https://google.com">Google</a> <a href="https://bing.com">Bing</a> <a href="https://forbes.com">Forbes</a> </nav>
ngForm
directive, and then used this knowledge to create our own directive for working with external links. We hope this technique is useful to you.Source: https://habr.com/ru/post/421345/
All Articles