Моя форма возвращает нулевое значение при отправке Angular - PullRequest
0 голосов
/ 11 апреля 2020

Я работаю над личным проектом с Angular. Я занимаю формы, но когда я отправляю свою форму с помощью кнопки отправки, ее значение равно нулю. Это код HTML

<form [formGroup]="checkoutform" (ngSubmit)="onSubmit($event)">
<mat-form-field class="example-full-width">
    <mat-label>Nro en Pokedex</mat-label>
    <input matInput placeholder="Ingrese ID Pokemon"
    class="input"
    formControlName="pokeid">
</mat-form-field>
<div *ngIf="checkoutform.get('pokeid').errors && checkoutform.get('pokeid').dirty">
    <p class="pp" *ngIf="checkoutform.get('pokeid').hasError('required')">Este campo es obliatorio</p>
    <p class="pp" *ngIf="checkoutform.get('pokeid').hasError('pattern')">Solo numeros</p>
</div>
<div class="containerButton">
    <button mat-raised-button color="primary"
    class="button"
    [disabled]="checkoutform.invalid"
    type="submit"
    >Buscar Pokemon</button>
</div>

Это код TS:

   import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { PokeServiceService} from './../../../core/services/poke-service.service';

@Component({
  selector: 'app-bar-search',
  templateUrl: './bar-search.component.html',
  styleUrls: ['./bar-search.component.scss']
})
export class BarSearchComponent implements OnInit {
  checkoutform;
  constructor(
    private formbuilder: FormBuilder,
    private pokeservice: PokeServiceService
  ) {
    this.buildForm();
   }

  ngOnInit(): void {
  }
  private buildForm() {
    this.checkoutform = this.formbuilder.group({
      pokeid: ['', [Validators.required, Validators.pattern('^[0-9]*$')]],
    });
  }
  get pokeidField() {
    return this.checkoutform.get('pokeid');
  }
  onSubmit(event: Event) {
    event.preventDefault();
    this.checkoutform.reset();
    if (this.checkoutform.valid) {
      var poked = this.checkoutform.value;
      this.pokeservice.getPokebyID(poked)
      .subscribe((newPoke) => {
        console.log(newPoke);
      });
    } else {
      console.log(this.checkoutform.value);
      console.log(poked.pokeid);
      console.log('error');
    }
    }
  }

В коде TS реализуйте файл console.log, чтобы увидеть значение каждой переменной, но все они возвращают мне ноль

enter image description here

1 Ответ

1 голос
/ 11 апреля 2020

Проблема с вашим кодом - вызов формы сброса. он установит pokeid элемента управления формы в null.

, вы должны изменить код, как показано ниже.

onSubmit(event: Event) {
    event.preventDefault();
    if (this.checkoutform.valid) {
      var poked = this.checkoutform.value;
      this.pokeservice.getPokebyID(poked).subscribe(newPoke => {
        console.log(newPoke);
        this.checkoutform.reset();
      });
    } else {
      console.log(this.checkoutform.value);
      console.log(poked.pokeid);
      console.log("error");
    }
  }
}

вы можете сбросить форму в блоке подписки на вызовы API.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...