I'm implementing a custom directive in Angular 2, directive for form validation, and in many places I see that in the directive definition the selector property is associated with multiple ids - for example:
@Directive({
selector: '[my-custom-validator][ngModel]'
})
What does the multiple '[...]' (brackets) selection mean?
Two or more components use the same element selector. Because there can only be a single component associated with an element, selectors must be unique strings to prevent ambiguity for Angular.
To create a custom directive we have to replace @Component decorator with @Directive decorator. So, let's get started with creating our first Custom Attribute directive. In this directive, we are going to highlight the selected DOM element by setting an element's background color. Create an app-highlight.
As in CSS, the selector [attr]
matches elements that have an attribute named attr
. When multiple attribute selectors are chained together, all the attributes must exist on the element.
Note: Unlike CSS, Angular ignores any [...]
or [(...)]
binding brackets on the target attribute when it performs the match.
Thus, the selector [my-custom-validate][ngModel]
matches elements that have both a my‑custom‑validate
attribute and an ngModel
attribute (including [ngModel]
and [(ngModel)]
). For example, the selector matches
<input type="text" name="username" my-custom-validate [(ngModel)]="model.username">
but not
<input type="text" name="username" my-custom-validate>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With