Error in getting value from input that has ngIf directive

I get an exception Error TypeError and Error Contextwhen I click the submit button. If I remove the directive ngIfIt will work as an excluded, 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);
 }

}

EDIT: I changed my form tag to <form (ngSubmit)="onSubmit(firstPlayer?.value, secondPlayer?.value)">and now print it for the inputPlayer input console and instead of secondPlayer its printsnull

Thanks for any help :)

+4
source share
2 answers

- , . , , , *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 node. node DOM - . - , ng- ( , DOM- ngIf) . .


, .. ... , :)

+2

*ngIf. , :

onSubmit(firstPlayer?.value, secondPlayer?.value)

onSubmit, HTML firstPlayer secondePlayer HTMLObject.

:

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

HTML (ngSubmit) :

<form (ngSubmit)="onSubmit(firstPlayer, secondPlayer)">

...

<input id="firstPlayer" name="firstPlayer" type="text" class="validate">
...

... .

undefined, [ngModel]="firstPlayer" , .

+2

Source: https://habr.com/ru/post/1695543/


All Articles