【问题标题】:Angular 4 template error: 'anonymous' does not contain such a memberAngular 4 模板错误:“匿名”不包含这样的成员
【发布时间】:2017-12-08 13:25:01
【问题描述】:

Angular 4写在Typescript 2.3.4

component.ts

/**
 * Info that drives the tabs in the template. Array is filled
 * in ngOnInit() once data is received from the server
 */
public tabs:Array<{
  title:string,
  description:string,
  data:Array<{name:string}>
}>=[];

component.html

<section *ngFor="let t of tabs">
  ...
  <div *ngFor="let i of t.data">{{i.name}}</div>
                                  ^^^^^^
</section>

编译器错误

Angular:未定义标识符“名称”。 &lt;anonymous&gt; 不包含这样的成员

起初我以为这与my other issue 相关联,但这次有所不同,因为tabs 模型的形状没有歧义:组件清楚地表明name 是@ 的每个成员的属性987654329@数组,本身就是tabs数组每个成员的属性。

这里发生了什么?

【问题讨论】:

  • 在哪里将数据分配到选项卡中?请在这里发帖。 bcz 我测试你的代码工作正常
  • @ShaileshLadumor 即使我从不分配任何东西(例如:如果我删除我的ngOnInit()),也会引发此错误;所以错误不是由数据如何分配给tabs引起的。请记住,错误发生在我的代码编辑器中,而不是在运行时,因此它与从服务器返回的数据没有任何关系
  • 我测试了您的代码,但工作正常。在 onNgInit() 中分配 dayta 选项卡并将其打印到 tamplate/.
  • 您在使用插件语言服务吗?你用的是哪个编辑器?
  • 我在使用带有 VS Code 的 Angular 语言服务扩展时遇到了同样的错误。我认为这是 Angular 语言服务中的一个错误,但我还没有找到任何解决方法。

标签: angular typescript angular-template


【解决方案1】:

尝试在绑定中添加安全导航运算符 (?),它允许您在路径最初可能有效也可能无效的情况下导航对象路径。

  <div *ngFor="let i of t.data">{{i?.name}}</div>

【讨论】:

    【解决方案2】:

    解决方案有效!

    这给了我这个信息:

    未定义标识符“问题”。 '' 不包含这样的成员

    加下划线

    <div class="card-header">
              {{q.question}}  <!- underline this line with red color -->
                ^^^^^^^^^^
    </div>
    

    这是一个打字稿问题,您必须将选项卡声明为任意类型以避免此问题
    tabs : any [];

    【讨论】:

    • 将类型声明为any 会消除对该变量的所有类型支持。因为我在其他地方使用了该变量(在我的打字稿文件中,而不仅仅是模板中),所以我想保持其类型的明确定义。这对我来说不是一个好的解决方案,但很高兴它对你有用。感谢分享。
    猜你喜欢
    • 2018-02-18
    • 1970-01-01
    • 2022-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-12
    • 2021-09-02
    • 1970-01-01
    相关资源
    最近更新 更多