将数据从子组件发送到父组件

时间:2017-04-17 17:14:21

标签: javascript angular output angular2-forms

我的子组件上有一个按钮,它应该向其父组件发送信息,但是此按钮不会发送此信息。我可能错过了一些东西,但我仍然没有注意到它。

以下是我的子组件内按钮的代码(有两个按钮:selectPessoaJuridicaselectPessoaFisica

import { Component, Input, Output, EventEmitter} from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormArray, FormsModule, ReactiveFormsModule} from '@angular/forms';
import {FinalizaDisputaService} from '../services/finaliza-disputa.service';
import {FinalizaDisputaComponent} from './finaliza-disputa.component'

@Component({
    moduleId: module.id,
    selector: 'titular',
    templateUrl: 'dados-titular.component.html'
})
export class TitularComponent {
    // we will pass in address from App component
  @Input('group')
  public titularForm: FormGroup;
  @Input() submitted:any;
  @Input() indexNumber:any;
  @Output() modelChanged = new EventEmitter<boolean>();
  public isJuridica = false;
  classe = {
    pessoa_fisica: 'selected',
    pessoa_juridica: ''
  };

  constructor(private _fb: FormBuilder, private finalizaAcordo:FinalizaDisputaService) {} 

  selectPessoaFisica(e:boolean){
    e = false;
    this.classe.pessoa_fisica = "selected";
    this.isJuridica = false;
    this.classe.pessoa_juridica = "";
    this.modelChanged.emit(e)
  }

  selectPessoaJuridica(e:boolean){
    e = true;
    this.classe.pessoa_fisica = "";
    this.classe.pessoa_juridica = "selected";
    this.isJuridica = true;
    console.log("ativou", e)
    this.modelChanged.emit(e);
  }
}

那么,这应该做的是通知父母e现在是假的。

这是来自父组件的html:

<titular (modelChanged)="recebeValidators($event)" [indexNumber]="indice" [submitted]="submitted" [group]="formDadosBancarios.controls.dados_titular.controls[i]"></titular>

这是来自父组件的代码,我应该从erecebeValidators)收到值:

import { Component, OnChanges, OnInit, Input } from '@angular/core';
import { Http } from '@angular/http';
import { FormBuilder, FormGroup, Validators, FormArray, FormsModule, ReactiveFormsModule, AbstractControl, ValidatorFn } from '@angular/forms';
import { FinalizaDisputaService } from '../services/finaliza-disputa.service';
import {DisputaService} from '../../disputas/services/disputas.service';
import { dadosAcordo } from '../model/dados-acordo.interface';
import { TitularComponent } from './dados-titular.component';
import {Routes, RouterModule, Router, ActivatedRoute} from '@angular/router';

@Component({
  moduleId: module.id,
  selector: 'detalhes',
  templateUrl: `finaliza-disputa.component.html`,
  providers: [FinalizaDisputaService]
})

export class FinalizaDisputaComponent implements OnInit {
  public dados: dadosAcordo;
  disputa:any;
  public formDadosBancarios: FormGroup;
  public submitted: boolean;
  public events: any[] = [];
  public servError: any;
  public indice = 0;
  public loading = false;
  soma = 0;
  public servSuccess: any;
  @Input() e:boolean;
  cpf_REGEXP = /^\d+$/;

  constructor(private _fb: FormBuilder, private service:DisputaService, private finalizaAcordo: FinalizaDisputaService,
   private route:ActivatedRoute, private router:Router) {}

  ngOnInit() {
    this.route.params.subscribe(params => {
      let id = params['id'];
      this.service
        .buscaPorId(id)
        .subscribe(disputa => {
          this.disputa = disputa;
          console.log(disputa.campanha);
          console.log(this.disputa.propostas_realizadas);
        },
        erro => console.log(erro));
    })

    this.formDadosBancarios = this._fb.group({
      id: [''],
      termos_condicoes: [false, Validators.requiredTrue],
      dados_titular: this._fb.array([
        this.initTitular()
      ])
    })
  }
  /**
  * initTitular- Inicializa o grupo de formulário dinâmico e suas validações
  * @returns  ''
  */
  initTitular() {
    return this._fb.group({
      titular: ['', [<any>Validators.required, <any>Validators.minLength(3)]],
      cnpj: [''],
      cpf: ['', <any>Validators.required],
      data_nasc: ['', <any>Validators.required],
      agencia: ['', <any>Validators.required],
      banco: ['', <any>Validators.required],
      conta: ['', <any>Validators.required],
      tipo: ['', <any>Validators.required],
      pessoa_juridica: [false],
      valor_deposito: ['']
    })
  }
  // this is where I receive e

  recebeValidators(model: dadosAcordo, e: any) {
    console.log("test", e);
    const array = <FormArray>this.formDadosBancarios.get('dados_titular');
    const cpf = array.at(this.indice).get("cpf");
    const cnpj = array.at(this.indice).get('cnpj');
    const data_nasc = array.at(this.indice).get('data_nasc');
    const cpfCtrl: AbstractControl = this.formDadosBancarios.get(['dados_titular', this.indice, 'cpf']);
    const pessoa_juridicaCtrl: AbstractControl = this.formDadosBancarios.get(['dados_titular', this.indice, 'pessoa_juridica'])
    const cnpjCtrl: AbstractControl = this.formDadosBancarios.get(['dados_titular', this.indice, 'cnpj']);
    const data_nascCtrl: AbstractControl = this.formDadosBancarios.get(['dados_titular', this.indice, 'data_nasc']);
    const reqValidators: ValidatorFn[] = [Validators.required, Validators.pattern(this.cpf_REGEXP)];
    if (e == true) {
      data_nascCtrl.clearValidators();
      cpfCtrl.clearValidators();
      cnpjCtrl.setValidators(reqValidators);
    }else{
      cnpjCtrl.clearValidators();
      cpfCtrl.setValidators(reqValidators);
      data_nascCtrl.setValidators(reqValidators);
    }
    data_nascCtrl.updateValueAndValidity();
    cpfCtrl.updateValueAndValidity();
    cnpjCtrl.updateValueAndValidity();
  }

但不是打印false而是打印undefined。有人能帮我吗?感谢

enter image description here

2 个答案:

答案 0 :(得分:2)

您似乎正在使用函数参数&#34; e&#34;遮蔽类属性。在&#34; recebeValidators&#34;功能

代码:

console.log("test", this.e);

实际应该是:

console.log("test", e);

要排除EventEmitter中可能出现的转换错误,请尝试不重用参数功能。例如:

selectPessoaFisica(e:any) {
    e = false;
    this.modelChanged.emit(e)
}

可以改写为:

selectPessoaFisica() {
    this.modelChanged.emit(false);
}

接收功能中还有一个额外的参数:

此:

recebeValidators(model: dadosAcordo, e: boolean) {

应该是:

recebeValidators(e: boolean) {

答案 1 :(得分:0)

你应该输入它

@Output() modelChanged = new EventEmitter<boolean>();

你也指的是一个错误的变量,你应该只传递一个参数,因为它在父组件中并删除了这个关键字

recebeValidators(e: boolean) {
    console.log("test", e);
}