The attribute directives are supposed to use selectors with selector:'[myDirective]'
syntax and then used in templates like <p myDirective ></p>'
. I also see that ngClass is an attribute directive and usage is like [ngClass]="'class1 class2'"
. I want to know when is square bracket used and when it is not. Is it related to some relation between directive selector and property binding with the same name ?

- 1,056
- 3
- 12
- 27
2 Answers
Square brackets are used when an expression need to be evaluated. ngClass can be used without brackets. Below code will treat class1 and class2 as normal string.
ngClass="class1 class2"

- 2,269
- 1
- 18
- 25
-
why is there no need of single quotes here ? – user2599052 Aug 22 '19 at 06:44
-
As ngClass don't have square brackets angular will treat class1 class2 as normal string. Ang if there was bracket it will treat them as variables. – ranjeet8082 Aug 22 '19 at 06:48
I think it depends on what kind of entity your are working with. In selectors you can, if you working on a component either write:
selector:'[myComponent]' => <div myComponent></div>
or
selector:'myComponent' => <myComponent></myComponent>
When it comes attribute binding, you could write
<div [title]="theTitleProperty"></div>
which will bind the html title attribute to the value of the components property theTitleProperty. (alt div title="{{theTitleProperty}}") while
<div title="theTitleProperty"></div>
will give the title the value 'theTitleProperty''
an alternative to ngClass could be
<div [class]="theClassProperty"></div>
And then its the @Inputs to a component. Any component might have an @Input you can use it with both bracket or not If you have a component with @Input() aText:string; you could use it like this:
<my-component [aText]="myTextProperty"></div>
And it would send the control property myTextProperty to the components @Input But if you write like this
<my-component aText="myTextProperty"></div>
It would send myTextProperty into the component.
Hope it helps a little

- 1,931
- 2
- 16
- 20