【发布时间】:2018-09-08 18:30:09
【问题描述】:
单击提交按钮时出现异常Error TypeError and Error Context。如果我将删除 ngIf 指令,它将作为例外工作,完整的 StackTrace:
PlayerNameFormComponent.html:8 ERROR TypeError: Cannot read property 'value' of undefined
at Object.eval [as handleEvent] (PlayerNameFormComponent.html:8)
at handleEvent (core.js:13547)
at callWithDebugContext (core.js:15056)
at Object.debugHandleEvent [as handleEvent] (core.js:14643)
at dispatchEvent (core.js:9962)
at eval (core.js:12301)
at SafeSubscriber.schedulerFn [as _next] (core.js:4343)
at SafeSubscriber.__tryOrUnsub (Subscriber.js:240)
at SafeSubscriber.next (Subscriber.js:187)
at Subscriber._next (Subscriber.js:128)
PlayerNameFormComponent.html
<form (ngSubmit)="onSubmit(firstPlayer.value, secondPlayer.value)"> // The line that throws the exception
<div class="input-field col s6">
<label for="firstPlayer">First Player Name</label>
<input #firstPlayer id="firstPlayer" name="firstPlayer" type="text" class="validate">
</div>
<div *ngIf="isMultiplePlayers" class="input-field col s6">
<label for="secondPlayer">Second Player Name</label>
<input #secondPlayer id="secondPlayer" name="secondPlayer" type="text" class="validate">
</div>
<button type="submit" class="waves-effect waves-light btn">Start</button>
</form>
PlayerNameFormComponent.ts
export class PlayerNameFormComponent {
isMultiplePlayers = true;
public onSubmit(firstPlayer: string, secondPlayer: string) {
console.log(firstPlayer);
console.log(secondPlayer);
}
}
编辑:
我将我的表单标签更改为 - <form (ngSubmit)="onSubmit(firstPlayer?.value, secondPlayer?.value)">,现在它的 print 用于控制台 firstPlayer 输入值,而不是 secondPlayer 值,它的 prints null
感谢您的任何帮助:)
【问题讨论】:
-
我们可以看看你在提交时做了什么吗?
-
firstPlayer或secondPlayer可能是undefined我会仔细检查你设置的位置并确保一切顺利 -
@Farasi78 请看我的编辑
-
为您的输入添加默认值怎么样?
-
@RadonirinaMaminiaina 我尝试添加默认值 the secondPlayer 该值在 onSubmit() 函数中仍然为空
标签: javascript angular angular-ng-if