Error TypeError and Error Context
单击提交按钮时出现异常。如果我删除ngIf
指令,它将像例外一样工作,Full 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)">
现在将其打印以管理firstPlayer输入值,而不是secondPlayer值打印null
感谢您的任何帮助:)
模板引用变量可以在模板中的任何位置访问,因此文档中的状态明确。本文对理解结构化指令(在本例中为)会很有帮助*ngIf
。
发生的事情*ngIf
是它创建了自己的模板,因此您可以在模板内部访问模板引用,模板*ngIf
只能由该范围创建,也可以在该范围内访问。
以下是网站摘录:
引发错误的示例代码:
<div *ngIf="true"> <my-component #variable [input]="'Do you see me?'> </div> {{ variable.input }}
原因是ngIf指令-或与星号(*)一起使用的任何其他指令。这些指令称为结构指令,而星号只是更复杂事物的简写形式。每次您使用结构性指令(ngIf,ngFor,ngSwitchCase等)时,Angular的视图引擎都会在两个步骤内将恒星减半(删除语法糖),使其最终形式变为以下最终形式(以先前的ngIf为例):
<ng-template [ngIf]="true"> ... </ng-template>`
你注意到了吗?在以前的包含结构指令的HTML中出现了一些与众不同的东西-ng-template节点。该节点是将模板引用变量的范围仅限制于此内部DOM部分的原因-它在内部定义了一个新模板。由于将变量限制为其定义模板,因此无法在ng-template(在ngIf的DOM部分内)中定义的任何变量使用。它不能越过模板的边界。
但是如何解决您的潜在问题,即获取值……您几乎已经设置了模板驱动的表单,因此您可以这样做,或者采用反应方式:)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句