如何绑定到Angular 2中的非本机属性?(How do I bind to a non

编程入门 行业动态 更新时间:2024-10-24 23:18:39
如何绑定到Angular 2中的非本机属性?(How do I bind to a non-native property in Angular 2?)

我正在尝试将值绑定到非本机的元素属性,显然通常的方法不起作用:

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

本文发布于:2023-08-05 07:13:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1430245.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:本机   绑定   属性   bind   Angular

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!