我有以下HTML
<announcements allowSelecting="true" (selectedItemChanged)="selectedItemChanged($event)"></announcements>
<form [style.visibility]="selectedItem!=undefined |styleVisibility">
<textarea [(ngModel)]="selectedItem.Message"></textarea>
<input type="number" step="0" [(ngModel)]="selectedItem.Ordering" />
</form>
基本上这是第一个组件公告,提供一个列表,然后用户可以从该列表中选择该项目,并且selectedItemChanged事件会导致该项目在主要组件中被选中,这就是2个控件上的内容页面绑定到。我知道还有很多与表单有关的内容,在我解决这个问题之后,我将对此进行调查。
我遇到的问题是页面错误地说明了selectedItem是未定义的,当页面首次加载时,它是未定义的。那么解决这个问题的“正确”方法是什么。
标记我考虑过使用ngIf并假设它会起作用,但如果我希望表单可见,在这种情况下我不会,但在其他我可能会这样做。
Gunter 如果我使用?,我会收到不同的错误。句法。在那种情况下,我收到此错误
Error: Uncaught (in promise): Template parse errors:
Parser Error: The '?.' operator cannot be used in the assignment at column 23 in [selectedItem?.Message=$event] in AnnouncementEditComponent@3:14 ("
@
<form [style.visibility]="selectedItem!=undefined |styleVisibility">
<textarea [ERROR ->][(ngModel)]="selectedItem?.Message"></textarea>
<input type="number" step="0" [(ngModel)]="selec"): AnnouncementEditComponent@3:14
我最初的方式错误是
EXCEPTION: Error in /app/announcements/announcementEdit.component.html:3:14
ORIGINAL EXCEPTION: TypeError: Unable to get property 'Message' of undefined or null reference
ORIGINAL STACKTRACE:
TypeError: Unable to get property 'Message' of undefined or null reference
at _View_AnnouncementEditComponent0.prototype.detectChangesInternal (Function code:178:3)
at AppView.prototype.detectChanges (eval code:12143:13)
at DebugAppView.prototype.detectChanges (eval code:12247:17)
at AppView.prototype.detectViewChildrenChanges (eval code:12169:17)
at AppView.prototype.detectChangesInternal (eval code:12154:13)
at AppView.prototype.detectChanges (eval code:12143:13)
at DebugAppView.prototype.detectChanges (eval code:12247:17)
at AppView.prototype.detectContentChildrenChanges (eval code:12161:17)
at AppView.prototype.detectChangesInternal (eval code:12153:13)
at AppView.prototype.detectChanges (eval code:12143:13)