angularjs - Angular 2 - @Input ne ažurira model na super komponenti


Imam sljedeći scenarij:

Postoje neke entitete koji posjeduju Pessoa, jedan od njih je Administrador, pa sam odlučio kreirati komponentu koja će obuhvatiti podatke Pessoa na CRUD obrascima. Povezao sam svojstvo administrador.pessoa s mojom novom PessoaFormComponent pomoću @Input() direktive.

Moj problem je što kada pošaljem obrazac AdministradorComponent, svojstvo administrador.pessoa ostaje null, kao da se ažuriranja svojstva pessoa u PessoaFormComponent ne odražavaju u 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();
 }
}

Odgovor #1

Za [(pessoa)]="entidade.pessoa" da bi ovaj sintaksis funkcionirao, potrebno je imati kombinaciju @Input() i @Output() gdje je naziv izlaza pessoaChange, a promjene vrijednosti se moraju emitirati koristeći 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);
  }