我想将一些数据绑定(bind)到非自定义 html 元素属性。但是,不推断属性中的 {{ }}。 我看过其他相关帖子“Angularjs templateUrl fails to bind attributes inside ng-repeat”,这是自定义指令的 Angular 1 解决方案。
例如,我有:
size = 500;
我希望以下 SVG 元素能够正常工作:
<svg xmlns="http://www.w3.org/2000/svg/" width="{{size}}" height="{{size}}">
<rect width="{{size}}" height="{{size}}" fill="#DCB35C"/>
</svg>
我应该如何在 Angular 2 中执行此操作?
最佳答案
简答
当 HTML 属性和 DOM 属性之间没有 1:1 映射时,必须使用 attribute binding syntax否则 Angular 2 将报告“模板解析错误”。
例子:
-
[attr.my-custom-attribute]="myComponentValue"
-
[attr.colspan]="1 + 1"
在您的情况下,SVG 元素具有宽度和高度 DOM 属性,但它们不是您所期望的。他们是 SVGAnimatedLength对象。尝试以旧方式设置它们的值不会有任何作用。这就是为什么您的模板没有按预期工作并且没有报告错误的原因。切换到属性绑定(bind)语法将修复此行为:[attr.width]="width" [attr.height]="height"
深入解释
属性绑定(bind)在 Angular 1 和 Angular 2 中的工作方式在概念上存在很大差异。
在 Angular 1 中,设置自定义属性如下所示:
-
<div a-custom-attribute="I am a custom {{ 'attribute' }}">Text Content</div>
-
<div ng-attr-a-custom-attribute="I am a custom {{ 'attribute' }}">Text Content</div>
- this syntax允许您绑定(bind)到浏览器急切处理的属性(例如 SVG 元素的 circle[cx] 属性、IMG 元素的 src 属性等)
在 Angular 2 中,情况有所不同:
Angular 2 的引入,正如他们所说, a new mental model :不是绑定(bind)到 HTML 属性,而是绑定(bind)到 DOM 属性。了解 the distinction between an HTML attribute and a DOM property对于掌握 Angular 2 绑定(bind)的工作原理至关重要。
绑定(bind)到 DOM 属性可能如下所示:
-
<img [src]="heroImageUrl">
-
<img bind-src="heroImageUrl">
-
<img src="{{ heroImageUrl }}">
- 这可能看起来有点令人困惑,特别是如果某人具有 AngularJS 1 背景,但 Angular 2 在呈现 View 之前将这些插值转换为相应的属性绑定(bind) (source)。 记住这一点很重要,作为Mark在评论部分指出,在计算插值后,然后将其结果转换为字符串 ( source )。这意味着此语法仅限于分配字符串值。
请注意,如果名称与 DOM 属性不匹配,Angular 2 会报告“未知 native 属性”错误:
// Template parse errors:
// Can't bind to 'colspan' since it isn't a known native property
<tr><td colspan="{{1 + 1}}">Three-Four</td></tr>
// Template parse errors:
// Can't bind to 'madeUpProperty' since it isn't a known native property
<div [madeUpProperty]="My custom {{ 'madeUpProperty' }}"></div>
这意味着必须使用 attribute binding syntax当没有要绑定(bind)的 DOM 属性时。
最后,我认为,作为一个好的经验法则,人们应该始终使用 property binding's syntax (例如 [src]="heroImageUrl"
)支持插值(例如 src="{{heroImageUrl}}"
),只要他想修改元素的 DOM 属性,因为后者仅限于传递字符串值。另一个原因是,如果某人具有 AngularJS 1 背景,这应该可以减少设置属性和 DOM 属性之间的混淆。
关于javascript - 如何在 html 元素属性中使用 Angular 2 外推?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36099392/