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

Angular中无法在HTML显示常量数据问题求助

问题解决方案

1. 修复常量文件的语法错误

原常量文件存在大量语法问题,直接导致数据无法被正确识别,修正后的代码如下:

export const CONTACT_US = {
  contactDetails: [
    {
      header: 'Customer Service',
      description: '1-877-743-3215'
    },
    {
      header: 'Hours of Operation',
      description: 'Monday-Friday: 8 a.m. -6 p.m. CT'
    }
  ]
};

错误点说明:

  • 变量名不能含空格,CONTACT US改为合法的CONTACT_US
  • 常量需赋值为对象,补充缺失的=和外层{}
  • 数组内的每个联系项必须用{}包裹成对象
  • 键值对、数组元素间需用英文逗号分隔
  • 统一使用英文单引号,修正原代码中的中文引号、未闭合引号

2. 修复组件文件的语法错误

组件生命周期函数拼写和结构错误,修正后代码:

import { Component, OnInit } from '@angular/core';
import { CONTACT_US } from './your-constant-file-path'; // 替换为实际文件路径

@Component({
  selector: 'app-contact',
  templateUrl: './contact.component.html',
  styleUrls: ['./contact.component.css']
})
export class ContactComponent implements OnInit {
  contactUs: any;

  ngOnInit(): void {
    this.contactUs = CONTACT_US;
  }
}

错误点说明:

  • 生命周期函数名是ngOnInit(首字母大写,驼峰命名),原代码拼写错误
  • 需实现OnInit接口并导入
  • ngOnInit需要完整的函数结构(括号、大括号)

3. 修复HTML模板的语法错误

原HTML指令语法、标签符号完全错误,无法绑定数据,修正后代码:

<div *ngFor="let contact of contactUs.contactDetails">
  <div>{{ contact.header }}</div>
  <span>{{ contact.description }}</span>
</div>

错误点说明:

  • ngFor指令正确写法是*ngFor="let item of collection",修正原代码的符号、引号位置错误
  • 使用Angular插值语法{{ }}绑定动态数据,替换原硬编码内容
  • 标签必须用英文尖括号<>,修正原代码中的中文尖括号和错误符号

完成以上三步后,常量中的联系信息即可正常在HTML中渲染。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 09:27:17