2

I have the following scenario:

There are some entities that own Pessoa, one of these is Administrador, so I decided to create a component to wrap the Pessoa data on CRUD forms. I bound the administrador.pessoa property to my new PessoaFormComponent with the @Input() directive.

My problem is that when I submit the AdministradorComponent form, the administrador.pessoa property remains null, like if the updates on pessoa property of PessoaFormComponent were not reflected into AdministradorComponent.

administrador.component.ts:

@Component({
...
templateUrl: './administrador.component.html',
directives: [... PessoaFormComponent, ...],
...
})
export class AdministradorComponent {
  @ViewChild('pessoaForm')
  pessoaFormComponent: PessoaFormComponent;
}

administrador.component.html:

...
<app-pessoa-form #pessoaForm [(pessoa)]="entidade.pessoa"></app-pessoa-form>
...

pessoa.form.component.ts:

@Component({
...
selector: 'app-pessoa-form',
templateUrl: './pessoa.form.component.html',
...
})
export class PessoaFormComponent implements AfterViewInit {
  @Input()
  pessoa: Pessoa;

  private _tipoPessoa: String;

 ngAfterViewInit() {
   this._tipoPessoa= 'FISICA';
   this.reiniciarPessoa();
 }

 private reiniciarPessoa() {
   if (this._tipoPessoa === 'JURIDICA') {
     this.pessoa = new PessoaJuridica();;
   } else {
     this.pessoa = new PessoaFisica();;
   }
 }

 get tipoPessoa(): String {
   return this._tipoPessoa;
 }

 set tipoPessoa(tipoPessoa: String) {
   this._tipoPessoa = tipoPessoa;
   this.reiniciarPessoa();
 }
}

1 Answer 1

2

For [(pessoa)]="entidade.pessoa" this syntax to work you need an @Input() and @Output() combination where the output name is pessoaChange and value changes need to be emitted using this.pessoaChange.emit(newValue)

export class PessoaFormComponent implements AfterViewInit {
  @Input()
  pessoa: Pessoa;

  @Output()
  pessoaChange:EventEmitter<Pessoa> = new EventEmitter<Pessoa>();

  private reiniciarPessoa() {
    if (this._tipoPessoa === 'JURIDICA') {
      this.pessoa = new PessoaJuridica();
    } else {
      this.pessoa = new PessoaFisica();;
    }
    this.pessoaChange.emit(this.pessoa);
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.