从具有ngIf指令的输入获取值时出错

Ron*_*dur 5 javascript angular-ng-if angular

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)
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

PlayerNameFormComponent.ts

export class PlayerNameFormComponent {
  isMultiplePlayers = true;

 public onSubmit(firstPlayer: string, secondPlayer: string) {
   console.log(firstPlayer);
   console.log(secondPlayer);
 }

}
Run Code Online (Sandbox Code Playgroud)

编辑: 我将表单标签更改为- <form (ngSubmit)="onSubmit(firstPlayer?.value, secondPlayer?.value)">现在将其打印以管理firstPlayer输入值,而不是secondPlayer值打印null

感谢您的任何帮助:)

AJT*_*T82 5

模板引用变量可以在模板中的任何位置访问,因此文档说明得很清楚。本文对于理解结构指令会发生什么非常有帮助,在本例中是您的*ngIf.

所发生的情况*ngIf是,它创建了自己的模板,因此您的模板引用可以在模板内部访问,该模板是由该范围创建的,*ngIf并且只能在该范围内访问。

以下是该网站的摘录:

抛出错误的示例代码:

<div *ngIf="true">
  <my-component #variable [input]="'Do you see me?'>
</div>
{{ variable.input }}
Run Code Online (Sandbox Code Playgroud)

其原因是 ngIf 指令 - 或与星号 (*) 一起使用的任何其他指令。这些指令被称为结构指令,星号只是更复杂的指令的缩写形式。每次使用结构指令(ngIf、ngFor、ngSwitchCase...)时,Angular 的视图引擎都会在两步内将星号脱糖(它删除语法糖),使其变为以下最终形式(以之前的 ngIf 为例):

<ng-template [ngIf]="true">
...
</ng-template>`
Run Code Online (Sandbox Code Playgroud)

你注意到了吗?之前包含结构指令的 HTML 中出现了一些非凡的东西 - ng-template 节点。该节点是将模板引用变量的范围限制为仅此内部 DOM 部分的原因 - 它在内部定义了一个新模板。由于将变量限制为其定义模板,因此在 ng-template 内(这意味着在 ngIf 的 DOM 部分内)定义的任何变量都不能在其外部使用。它不能跨越模板的边界。


但是如何解决您的根本问题,即获取值...您几乎已经设置了模板驱动的表单,因此您可以这样做,或者然后采用反应方式:)