1

In angular 2, when I want to style a specific component I use the following:

<div #mask id="mask" class="col-xs-12 some-generi-ccss-class"></div>

// in .css
#mask{
  height: 50px;
}

In my opinion it seems like a bit of a double handle defining both an id (id="mask") to style with and a ng2 selector string (#mask) to use with @ViewChild('mask') in my component.ts for the one element.

Am I able to drop one of these attributes but still achieve both functionalities? Or is this boilerplate?

Zze
  • 18,229
  • 13
  • 85
  • 118
  • `#mask` is unrelated to styling and unrelated to id. It just allows you to reference the `
    ` from other places in the template or using `@ViewChild()`. See for example http://stackoverflow.com/questions/32693061/angular-2-typescript-get-hold-of-an-element-in-the-template/35209681#35209681 to learn what a template variable can be used for.
    – Günter Zöchbauer Mar 31 '17 at 05:20
  • Thanks @GünterZöchbauer – Zze Apr 02 '17 at 22:35
  • 1
    @GünterZöchbauer Do you want to post this as an answer so I can finish this question with an accepted answer? – Zze Apr 18 '17 at 23:26

2 Answers2

0

Answer is no and yes :

Coz it looks same but both are different :

#mask in div elements shows the template variable , so you can access it inside template and in component , that's part of angular 2

id="mask" is html's default attribute,

Though if you want to access the div without using #mask , there is way , via document.getElementById('mask') and remove #mask if you don't want to access it from template side.

Vivek Doshi
  • 56,649
  • 12
  • 110
  • 122
  • This is just another way , if he wants to. – Vivek Doshi Mar 31 '17 at 03:14
  • He wants to **style** the element, not retrieve it programmatically. So why is the answer "no and yes"? If the question is *Am I able to drop one of these attributes but still achieve both functionalities?*, then the answer is **no**. –  Mar 31 '17 at 04:06
  • Am I able to drop one of these attributes but still achieve both functionalities? yes or no for this. – Vivek Doshi Mar 31 '17 at 04:28
  • not retrieve it programmatically ? then why he described @ViewChild('mask') , please read whole query. And I have just give him option , if he want to access. – Vivek Doshi Mar 31 '17 at 04:29
  • Read the question carefully, especially the part which says **to style with**. –  Mar 31 '17 at 05:19
0

#mask is unrelated to styling and unrelated to "id".
It just allows you to reference the <div> from other places within the template from using @ViewChild(...), @ContentChild(...) (@ViewChildren(...), @ContentChildren(...)).

See for example stackoverflow.com/questions/32693061/… to learn what a template variable can be used for.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567