简体   繁体   中英

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>

Try this:

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM