boysimple dimple
boysimple dimple

Reputation: 199

How can a custom attribute of a component be accessed? (Angular 5)

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?

Upvotes: 1

Views: 4347

Answers (2)

user3620541
user3620541

Reputation: 21

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

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

Upvotes: 2

Estus Flask
Estus Flask

Reputation: 222498

[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).

Upvotes: 2

Related Questions