anecsa
anecsa

Reputation: 11

Angular6/Typescript - ERROR when trying to Add Object to Array

I am failing to add a class into my Array. Error message: ERROR TypeError: Cannot read property 'value' of undefined

class

   export class Essensplan {

   id: number;
   EssenProWoche: number[] = new Array(5);

  }

service.ts

 / POST: add a new essensplan to the server */
  addEssensplan(essensplan: Essensplan): Observable<Essensplan> {
    return this.http.post<Essensplan>(this.essensplanUrl, essensplan, 
httpOptions).pipe(
      tap((essensplan: Essensplan) => this.log(added essen w/ 
id=${essensplan.id})),
      catchError(this.handleError<Essensplan>('addEssensplan'))
   );
  }

component

  addEssensplan(id: number): void {
    // id = id.trim();
    if (!id) { return; }
    this.essensplanService.addEssensplan({ id } as Essensplan)
      .subscribe(essensplan => {
        this.essensplan.push(essensplan);
        this.changeDetector.markForCheck();
      });
  }

Template**

<div>
  <label>Essensplan Woche:
<input type=number #Wochennummer />
  </label>
  <!-- (click) passes input value to add() and then clears the input -->
  <button (click)="addEssensplan(essensplanid.value); essensplanid.value=''">
    add
  </button>

It seems like it can not read an ID in the Text field, is it possible to convert the String (?) input into a number

Upvotes: 0

Views: 141

Answers (1)

Ascena
Ascena

Reputation: 60

your essensplanid.value is not defined, because in the input you wrote #Wochennummer.

just change essensplan.id to #Wochennummer or the other way

<div>
 <label>Essensplan Woche:
    <input type="number"  #Wochennummer />
  </label>
  <!-- (click) passes input value to add() and then clears the input -->
  <button (click)="addEssensplan(Wochennummer.value); Wochennummer.value=''">
   add
   </button>
</div>

Upvotes: 1

Related Questions