1

I've got a component called phrase, which is used like this:

<phrase *ngFor="let phrase of phraseList.phrases" [attachedPhrase]="phrase"></phrase>

Let's say now, I get one of these phrase components using jQuery. How do I access attachedPhrase?

  • Here you are using ngFor. My question is if you just want to get a specific one or all ? – Ulrich Dohou Dec 17 '17 at 13:26
  • The specific one that belongs to this element. – boysimple dimple Dec 17 '17 at 13:27
  • There are ViewChild, ElementRef and attr() that you can use. I can help you providing a good answer but Can you provide a clear use case ? – Ulrich Dohou Dec 17 '17 at 13:29
  • My application unfortunately makes use of some dirty jquery on keyboard events to return the phrase component I'm interested in. https://imgur.com/GghcsKt, Now, I need to use that DOM element to get the phrase object attached to it. – boysimple dimple Dec 17 '17 at 13:36

2 Answers2

2

[attachedPhrase] is not an attribute but property binding. It is supposed to be available only inside Angular application.

Although it's possible to access it as ng-reflect-* attribute, this can be recommended only for debugging purposes (this is the reason why these attributes are available in debugging mode only).

Considering that phrase is a string and attachedPhrase should be available both as component input and DOM attribute, it should be changed to attribute binding:

<phrase *ngFor="let phrase of phraseList.phrases" attachedPhrase="{{ phrase }}"></phrase>

Since attributes are case insensitive, it will be compiled to

<phrase attachedphrase="..."></phrase>

Property and attribute bindings can be interchangeable, but only if the expression is expected to be interpolated to a string.

Whenever possible, it's always preferable to not rely on DOM selectors and provide $(...) with actual reference to DOM element (nativeElement property of ViewChild or ElementRef element reference).

Estus Flask
  • 206,104
  • 70
  • 425
  • 565
2

You can try: [attr.attachedPhrase]="'phase'".

Detailed info you can check out this site about Angular 5 directive.

Milo
  • 3,365
  • 9
  • 30
  • 44