Angular露营列表添加功能报错求助:ngModule绑定等问题
Angular露营应用报错排查与修复
报错清单
Can't bind to 'ngModule' since it isn't a known property of 'input'Type 'Event' is not assignable to type 'string'localhost:4200无法访问
具体修复步骤
1. 修正双向绑定指令拼写错误
在 campinginvoer.component.html 中,Angular双向绑定指令被误写为 ngModule,正确指令应为 ngModel:
修改前:
<input type="text" id="CampingNaam" [(ngModule)]="InvoerCampingNaam">
修改后:
<input type="text" id="CampingNaam" [(ngModel)]="InvoerCampingNaam">
2. 修复按钮事件绑定语法错误
campinginvoer.component.html 中按钮的事件绑定位置错误,需将 (click) 事件放在标签属性内,而非标签内容中:
修改前:
<button> (click)="onCreateCamping()">Invoeren</button>
修改后:
<button (click)="onCreateCamping()">Invoeren</button>
3. 解决本地服务无法访问问题
localhost:4200 无法打开是因为上述语法错误导致Angular编译失败,修复后按以下步骤操作:
- 停止当前运行的Angular服务(按
Ctrl+C) - 重新启动服务:
ng serve - 编译完成后访问
http://localhost:4200
额外功能完善(可选)
当前点击按钮仅打印输入内容,若要将新增露营添加到列表,需补充父子组件通信逻辑:
步骤1:在输入组件中添加事件发射器
修改 campinginvoer.component.ts:
import { Component, Output, EventEmitter } from "@angular/core"; @Component({ selector: 'app-camping-invoer', templateUrl: './campinginvoer.component.html' }) export class CampingInvoerComponent { InvoerCampingNaam = ''; @Output() campingAdded = new EventEmitter<string>(); onCreateCamping() { if (this.InvoerCampingNaam.trim()) { this.campingAdded.emit(this.InvoerCampingNaam); this.InvoerCampingNaam = ''; } } }
步骤2:在根组件中接收事件并更新列表
修改 app.component.html:
<app-camping-invoer (campingAdded)="campings.push($event)"></app-camping-invoer> <app-camping [campingList]="campings"></app-camping>
内容的提问来源于stack exchange,提问作者Miranda
相关产品推荐
相关产品推荐

