You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular为何显示原始HTML?插值绑定失效问题求助

Angular插值表达式无法解析问题排查

刚学Angular,设置的插值值无法在HTML中解析,页面仅显示原始的{{}}语法,未渲染出对应数据。

相关代码

HTML模板代码

<p>to-do-items works!</p>
<h2>{{toDoItems.name}} Details</h2>
<div><span>id: </span>{{toDoItems.id}}</div>
<div><span>name:</span>{{toDoItems.name}}</div>
<div><span>is complete: </span>{{toDoItems.isComplete}}</div>

组件TypeScript代码

import { Component, OnInit} from '@angular/core';
import {ToDoItem} from "../to-do-item";

@Component({
  selector: 'app-to-do-items',
  templateUrl: './to-do-items.component.html',
  styleUrls: ['./to-do-items.component.css']
})
export class ToDoItemsComponent implements OnInit{
toDoItems: ToDoItem = {
  id: 1,
  name: "Danny",
  isComplete: false
}

constructor(){}
  ngOnInit() {
  }
}

ToDoItem类声明代码

export class ToDoItem{
      constructor(
      public id: number,
      public name: string,
      public isComplete: boolean
    ){}
}

解决方法

  • 修正ToDoItem实例化方式:ToDoItem是带构造函数的类,不能直接用对象字面量赋值,需通过new关键字创建实例:
    toDoItems: ToDoItem = new ToDoItem(1, "Danny", false);
    
  • 确认组件已注册到模块:检查项目根模块(如AppModule)或对应功能模块的declarations数组,确保ToDoItemsComponent已被添加:
    @NgModule({
      declarations: [
        AppComponent,
        ToDoItemsComponent // 必须包含该组件
      ],
      // ...其他配置
    })
    export class AppModule { }
    
  • 检查根组件是否使用组件选择器:在app.component.html中添加组件标签:
    <app-to-do-items></app-to-do-items>
    
  • 查看控制台错误信息:启动项目后打开浏览器开发者工具,检查Console面板的编译/运行时错误,根据提示进一步排查。

内容的提问来源于stack exchange,提问作者Larrythelobster

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 08:02:14