Я не могу изменить форму Angular - PullRequest
1 голос
/ 11 января 2020

У меня есть этот код в моем component.ts, который заполняет форму данными пользователя, который получает идентификатор в качестве параметра

export class EditComponent implements OnInit {

    async ngOnInit() {
    await this.makeForm(this.user);
    this.activatedRoute.params.subscribe(
      params => this.userService.getUser(params.id).subscribe(
        resp => this.user = resp
      )
      );
  }
  async getUserId(id: number) {
    await this.userService.getUser(id).subscribe(
      resp => {
        this.user = resp;
        this.formulario.controls.nombre.setValue(this.user['nombre'])
        console.log(this.formulario)
      },
      err => console.log(err)
    );
  }
   makeForm(user) {
    console.log(user);
    this.formulario = this.formBuilder.group({
      name: ['', Validators.required],
      lastname: ['', Validators.required],
      country: ['', Validators.required],
      city: ['', Validators.required]
    });
  }
  ngDoCheck () {
    if (this.user && this.formulario) {
      // tslint:disable: no-string-literal
      this.formulario.controls.name.setValue(this.user['nombre'].toString());
      this.formulario.controls.lastname.setValue(this.user['apellidos'].toString());
      this.formulario.controls.country.setValue(this.user['pais'].toString());
      this.formulario.controls.city.setValue(this.user['ciudad'].toString());
    }
  }
  updateUser() {
    this.submitted = true;
    console.log(this.formulario);
    if (this.formulario.invalid) {
      return;
    }
    const data = {
      id: this.user['id'],
      nombre: this.formulario.value.name,
      apellidos: this.formulario.value.lastname,
      fechaNacimiento: date,
      pais: this.formulario.value.country,
      ciudad: this.formulario.value.city
    };
    this.userService.updateUser(data).subscribe(
      resp => this.router.navigate(['']),
      err => console.log(err)
    );
  }
}

И это код html для ввода

form [formGroup]="formulario" class="form">
            <table cellspacing="0">
              <tr>
                <td>
                  <mat-form-field>
                    <input
                      matInput
                      value="{{ user.nombre }}"
                      formControlName="name"
                      class="full-width"
                    />
                  </mat-form-field>
                </td>
              </tr>

Проблема в том, что входные данные остаются с пользовательской информацией, и они не могут быть изменены, вы не можете записывать в них и не удалять, они остаются только stati c, и я не знаю, что возможно. Если я не заполняю форму, то при отправке ее появляются пустые значения.

1 Ответ

1 голос
/ 12 января 2020

Мне удалось это исправить

export class EditComponent implements OnInit {

  user: User[];
  formulario = new FormGroup({
    name: new FormControl('', Validators.required),
    lastname: new FormControl('', Validators.required),
    country: new FormControl('', Validators.required),
    city: new FormControl('', Validators.required),
  });
   // tslint:disable-next-line: no-inferrable-types
   submitted: boolean = false;
  constructor(private userService: UserService,  private activatedRoute: ActivatedRoute, private router: Router, 
              private formBuilder: FormBuilder) {
                this.activatedRoute.params.subscribe(
                  params => this.getUserId(params.id)
                  );
               }
  ngOnInit() {
    this.fillForm();
  }
   getUserId(id: number) {
    this.userService.getUser(id).subscribe(
      resp => {
        this.user = resp;
        this.fillForm();
      },
      err => console.log(err)
    );
    console.log(this.user);
  }
  fillForm() {
    if (this.user && this.formulario) {
      // tslint:disable: no-string-literal
      this.formulario.controls.name.setValue(this.user['nombre'].toString());
      this.formulario.controls.lastname.setValue(this.user['apellidos'].toString());
      this.formulario.controls.country.setValue(this.user['pais'].toString());
      this.formulario.controls.city.setValue(this.user['ciudad'].toString());
    }
  }
  borrarUsuario() {
    // tslint:disable-next-line: no-string-literal
    this.userService.removeUser(this.user['id']).subscribe(
      resp => this.router.navigate(['']),
      err => console.log(err)
    );
  }
  updateUser() {
    this.submitted = true;
    console.log(this.formulario);
    if (this.formulario.invalid) {
      return;
    }
    const date = moment(this.formulario.value.date).format('YYYY-MM-DD');
    const data = {
      // tslint:disable-next-line: no-string-literal
      id: this.user['id'],
      nombre: this.formulario.value.name,
      apellidos: this.formulario.value.lastname,
      fechaNacimiento: date,
      pais: this.formulario.value.country,
      ciudad: this.formulario.value.city
    };
    console.log(data);
    this.userService.updateUser(data).subscribe(
      resp => this.router.navigate(['']),
      err => console.log(err)
    );
  }
}

Самые большие изменения были: удалите ngDoCheck и запустите форму перед конструктором, в дополнение к заполнению формы при поиске пользовательских данных

...