我正在尝试将值绑定到非本机的元素属性,显然通常的方法不起作用:
import {Directive, ElementRef, Input, OnInit, HostBinding} from 'angular2/core'; @Directive({ selector: '[myFeet]' }) export class MyFeetDirective { @HostBinding('feet') @Input() feetProps:string constructor(private el: ElementRef) { } }我正在引用这个指令:
<div [myFeet]="body.footCount"></div>我希望这是DOM中的最终结果(即后角度渲染):
<div feet="2"></div>我设法通过简单地使用ngOnInit函数来实现这一点,该函数设置如下属性:
ngOnInit(){ this._setAttributes(); } private _setAttributes(){ if (this._feetProps != null) { this._el.nativeElement.setAttribute("feet", this._feetProps); } }但这不是Angular方式,我想知道是什么?
ps我认为Angular 2的性能优势在某种程度上与坚持原生DOM有关,但有没有办法覆盖自定义元素/属性? 也许这是错的,无论哪种方式,我都很感激你的见解。
I'm trying to bind values to an element attribute that is non-native and obviously the usual approach isn't working:
import {Directive, ElementRef, Input, OnInit, HostBinding} from 'angular2/core'; @Directive({ selector: '[myFeet]' }) export class MyFeetDirective { @HostBinding('feet') @Input() feetProps:string constructor(private el: ElementRef) { } }I'm referencing this directive like this:
<div [myFeet]="body.footCount"></div>And I want this to be the end result in the DOM (i.e. post-Angular rendering):
<div feet="2"></div>I have managed to achieve this by simply using an ngOnInit function that sets the attributes like so:
ngOnInit(){ this._setAttributes(); } private _setAttributes(){ if (this._feetProps != null) { this._el.nativeElement.setAttribute("feet", this._feetProps); } }But this isn't the Angular way and I wondered what is?
p.s. I think the performance benefits of Angular 2 are in some way linked to the adherence to the native DOM, but is there a way to override this for custom elements/attributes? Maybe this is wrong, either way, I'd appreciate your insight.
最满意答案
如果要将属性添加到DOM使用属性绑定语法而不是属性绑定语法。
@Directive({ selector: '[myFeet]' }) export class MyFeetDirective { @HostBinding('attr.feet') @Input() feetProps:string }If you want the attribute to be added to the DOM use attribute binding syntax instead of property binding syntax.
@Directive({ selector: '[myFeet]' }) export class MyFeetDirective { @HostBinding('attr.feet') @Input() feetProps:string }更多推荐
DOM,way,Angular,feet,电脑培训,计算机培训,IT培训"/> <meta name="descript
发布评论