Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 Directive - selector with multiple ids

Tags:

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?

like image 518
galvan Avatar asked Jul 19 '16 13:07

galvan


People also ask

Can two components have same selector?

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.

How do I create a custom directive?

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.


1 Answers

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>
like image 111
Michael Liu Avatar answered Sep 28 '22 01:09

Michael Liu