angularjs - Angular 2 - @Input 不更新 super 组件上的模型

标签 angularjs typescript angular

我有以下情况:

有一些实体拥有 Pessoa,其中之一是 Administrador,因此我决定创建一个组件来包装 Pessoa 数据在 CRUD 表单上。我使用 @Input() 指令将 administrador.pessoa 属性绑定(bind)到我的新 PessoaFormComponent

我的问题是,当我提交 AdministradorComponent 表单时,administrador.pessoa 属性仍为空,就像 pessoa 属性的更新一样PessoaFormComponent 未反射(reflect)到 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();
 }
}

最佳答案

要使 [(pessoa)]="entidade.pessoa" 这种语法起作用,您需要 @Input()@Output() 组合,其中输出名称为 pessoaChange 并且需要使用 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);
  }

关于angularjs - Angular 2 - @Input 不更新 super 组件上的模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37077309/

相关文章:

javascript - 将 JSON 重新格式化为数组以便在 AngularJs 中使用时出现问题

angular - 删除 HttpParams 中的空参数

Angular CLI 6 - 使用 Source Maps 构建 Angular 库

javascript - 从指令访问 Controller 功能

javascript - 我如何在 e2e 测试 Angular Protractor 中的标签中添加文本

TypeScript 在 for...of 中拒绝迭代器

javascript - 按符号过滤的柯里化(Currying)函数无法在 Typescript 中获得兼容的函数实现

Angular 2 ngClass - 应用多个类,带有类变量

asp.net-mvc-4 - signalR:/signalr/hubs不会生成

reactjs - 类型属性依赖于另一个属性的返回类型