【问题标题】:Angular 6 - How to read angular specific attributesAngular 6 - 如何读取角度特定属性
【发布时间】:2018-09-28 01:15:27
【问题描述】:

我有一个组件,我在其上指定 angular i18in 属性,如下所示:

<app-text i18n="meaning|description"> DeveloperText</app-text>

我希望能够读取此属性。我曾尝试使用 ElementRef 并访问 nativeElement,但是当我查看源代码时,属性 i18n 不是 DOM 元素的一部分。当我的应用程序启动时,DOM 如下所示:

<app-text _ngcontent-c0=""> DeveloperText</app-text>

那么我可以使用 Angular 框架以某种方式读取这样的属性吗?

【问题讨论】:

  • 我尝试使用@Input() i18n;在 AppText 组件上 - 但它始终未定义,因此它不起作用。我知道我可以在组件上创建一个属性 - 但是我会复制内容两次,例如像这样: DeveloperText。我真的不想这样做,除非真的无法读取 i18n 属性:)
  • 我不认为你可以访问 i18n 属性,因为 Angular 编译器会从 DOM 中删除它,在 Angular 文档中有解释。
  • @AliShahbaz,你能给我一个解释这个的链接吗?
  • angular.io/guide/i18n#mark-text-with-the-i18n-attributei18n is a custom attribute, recognized by Angular tools and compilers. After translation, the compiler removes it. It is not an Angular directive.

标签: javascript html angular typescript


【解决方案1】:

在您的 HTML 中:

<app-text #something i18n="meaning|description">DeveloperText</app-text>

在您的控制器中:

@ViewChild('something') fred;

您现在有了元素的句柄。如果你这样记录:

console.log(this.fred);
console.log(this.fred.nativeElement);

您应该找到您感兴趣的财产的价值。

【讨论】:

  • 好的简单解决方案,当 angular 最终赶上时易于更改
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-05
  • 2019-02-28
  • 2022-01-13
  • 1970-01-01
  • 1970-01-01
  • 2019-08-28
  • 1970-01-01
相关资源
最近更新 更多