0
votes

Two-way data binding does not work correctly.

Can I recover the data using {user | json}, but when using [(ngModel)] = "user.username" an error is displayed.

Interface

export interface UserModel {

        username?: any;
        email?: any;
        first_name: any;
        last_name: any;
        profile: ProfileModel;

}

interface ProfileModel {

        nome_empresa: any;
        cnpj: any;
}

componente

import { Component, OnInit } from '@angular/core';
import { PerfilService } from './perfil.service';
import { UserModel } from './user.model';

@Component({
  selector: 'mw-perfil',
  templateUrl: './perfil.component.html'
})
export class PerfilComponent implements OnInit {


  user: UserModel = new UserModel();

  constructor(private perfil: PerfilService) { }

  ngOnInit() {
    this.perfil.get().subscribe((perfil) => {
      this.user = perfil;

    })

  }

}

Template

<input id="username" class="form-control" data-error="Usuário inválido" placeholder="" required="required" type="text" name="username" [(ngModel)]="user.username">

PerfilComponent.html:31 ERROR TypeError: Cannot read property 'username' of undefined at Object.View_PerfilComponent_0._co [as updateDirectives] (PerfilComponent.html:31) at Object.debugUpdateDirectives [as updateDirectives] (core.es5.js:13058) at checkAndUpdateView (core.es5.js:12238) at callViewAction (core.es5.js:12603) at execComponentViewsAction (core.es5.js:12535) at checkAndUpdateView (core.es5.js:12244) at callViewAction (core.es5.js:12603) at execEmbeddedViewsAction (core.es5.js:12561) at checkAndUpdateView (core.es5.js:12239) at callViewAction (core.es5.js:12603)

1

1 Answers

0
votes

You are setting user by an asynchronous way. The data won't be ready even though you invoke the asynchronous call at ngOnInit.

Since your are using user.username at ngModel, the safe navigator operator can not be used here. So the only solution is initializing user first, below ways will solve the problem:

  // option1
  user: UserModel = new UserModel();

  // option2
  constructor(private perfil: PerfilService) { 
    this.user = new UserModel();
  }

  // option3
  ngOnInit() {
    this.user = new UserModel();
    this.perfil.get().subscribe((perfil) => {
      this.user = perfil;

    })
  }