JoeGeeky
JoeGeeky

Reputation: 3796

Custom attributes lead to errors when binding Angular templates

We are binding model data in component template markup which works until we attempt to bind data to custom attributes. We see errors such as Can't bind to 'x-version' since it isn't a known property of 'section' and different errors if we apply the bracketed pattern.

Essentially we are placing hidden data in the markup for other scripts to use within their processes. Can someone clarify what is happening and suggest ways to accomplish this?

We have attempted to apply the following two patterns and get errors on each. We are using Angular 2+

<section x-version="{{item?.version}}">
...
</section>

<section [x-version]="item?.version">
...
</section>

Upvotes: 1

Views: 345

Answers (3)

eneoes
eneoes

Reputation: 176

That error says that x-version should be a component defined @input. If it is not, you may want to use an attribute handler way like your first line

Upvotes: 0

Mehdi
Mehdi

Reputation: 2398

When you place an attribute on an html tag, Angular will try to find a corresponding Input element on the corresponding component, or a directive that is expecting that same attribute. in short, you need to create a Directive XVersion like so :

import { Directive, ElementRef,Renderer,Input} from '@angular/core';
@Directive({ 
    selector: '[x-version]'    
})

export class XVersion { 
    @Input versions;
    constructor(elementRef: ElementRef, renderer: Renderer) {  
        //Use elementRef, renderer, and this.version to manipulate the Dom here           
    }        
}

then use the attribute with square braquets.

Alternatively, you can try @DeborahK's solution, but I'm afraid the - in x-version will be a problem

Upvotes: 0

DeborahK
DeborahK

Reputation: 60528

Try this:

<section attr.x-version="{{item?.version}}">
...
</section>

<section [attr.x-version]="item?.version">
...
</section>

Upvotes: 3

Related Questions