单击按钮时,EventEmmiter不起作用

时间:2019-03-21 13:59:10

标签: javascript angular

我的系统中有一个屏幕,当您单击按钮时,将打开一个模式窗口。在此屏幕上,我有以下html:

info-atleta.component.html

<foot-play-edit-perfil-modal (sendValue)="receiveMessage($event)" 
[player]="player" [showModalEdit]="showModalEditPerfil"></foot-play- 
edit-perfil-modal>

info-atleta.component.ts

receiveMessage($event) {
   console.log('teste',$event)
}

在我的模式中,我有一些非常基本的表单字段,并带有一个刷新按钮

edit.perfil.modal.ts

    import { Component, OnInit, Input, ViewChild, ElementRef, Output, EventEmitter } from "@angular/core";
import { FormGroup, FormBuilder, Validators } from "@angular/forms";
import { ActivatedRoute } from "@angular/router";
import { EditPerfilModalModel } from './../../../../core/models/edit-perfil-modal.model';
import { EditPerfilModalService } from './../../../../core/http/edit-perfil-modal.service';
import swal from "sweetalert";

@Component({
  selector: "foot-play-edit-perfil-modal",
  templateUrl: "./edit-perfil-modal.component.html"
})
export class EditPerfilModalComponent implements OnInit {

  public cmModel: any;
  public heigthModel: any;
  public countryModelId: any;
  public cityModelId: any;
  public stateModelId: any;
  public day: any;
  public month: any;
  public year: any;
  public days = [];
  public months = [];
  public years = [];
  public cm = [];
  public positions = [];
  public position1Model: any;
  public position2Model: any;
  public dominantFootModelId: any;
  public dominantFoot = [];
  public countries = [];
  public states = [];
  public cities = [];
  public editPerfilModal: EditPerfilModalModel;

  @ViewChild("position1") position1: ElementRef;
  @ViewChild("position2") position2: ElementRef;
  @ViewChild("warning") warning: ElementRef;

  @Input() showModalEdit: boolean;
  @Input() player: any;

  @Output() sendValue = new EventEmitter();

  public profileForm: FormGroup;

  constructor(private fb: FormBuilder, private modalService: EditPerfilModalService, private route: ActivatedRoute) {    
    this.profileForm = fb.group({
      cityId: [null],
      countryId: [null],
      dominantFoot: [null, Validators.required],
      heigth: [null, Validators.required],
      lastName: [null, Validators.required],
      name: [null, Validators.required],
      nickname: [null, Validators.required],
      position1: [null, Validators.required],
      position2: [null, Validators.required],
      stateId: [null],
      birthMonth: [null, Validators.required],
      birthYear: [null, Validators.required]
    });    
  }

  ngOnInit() {
    this.sendMessage();
    this.editPerfilModal = new EditPerfilModalModel();
    this.position1Model = 0;
    this.position2Model = 0;
    this.dominantFootModelId = 0;
    this.editPerfilModal.height = null;
    this.stateModelId = 0;
    this.cityModelId = 0;
    this.countryModelId = 0;
    this.editPerfilModal.dominantFoot = null;
    this.day = null;
    this.month = null;
    this.year = null;
    this.editPerfilModal.id = parseInt(this.route.snapshot.paramMap.get("id"));
    this.cmModel = null;
    this.heigthModel = null;

    for (let day = 1; day < 32; day++) {
      this.days.push(day);
    }

    for (let month = 1; month < 13; month++) {
      if(month < 10){
        this.months.push('0'+month);
      }
      else{
        this.months.push(month);
      }
    }

    for (let cm = 1; cm < 100; cm++) {
      this.cm.push(cm);
    }

    for (let year = 1980; year <= 2019; year++) {
      this.years.push(year);
    }

    this.patchValueForm();    
    this.getCountry();
    this.getPosition();
    this.getDominatFoot();
    this.getProfile();

  }

  patchValueForm() {
    this.profileForm.patchValue({
      cityId: "",
      countryId: "",
      dominantFoot: "",
      heigth: "",
      lastName: "",
      name: "",
      nickname: "",
      position1: "",
      position2: "",
      stateId: "",
      birthMonth: "",
      birthYear: ""
    });
  }

  /**
  * Verifica se os campos da posição são iguais
  */

  changePosition() {

    // Cores padrões dos elementos
    this.position2.nativeElement.style.borderColor = "#BEBEBE";
    this.warning.nativeElement.style.display = "none";

    if (this.position1.nativeElement.value === this.position2.nativeElement.value) {
      // Mudança de cor ao verificar como resultados iguais
      this.position2.nativeElement.style.borderColor = "red";
      this.warning.nativeElement.style.display = "block";

      this.positions.filter((value, index) => {
        this.position2.nativeElement.value = !this.position1.nativeElement
        .value;
      });
    }
  }

  sendMessage() {

  }

  private getProfile(){
    this.modalService.getProfile(this.editPerfilModal.id).subscribe(data => {
      var res = data.data['birthday'].split("-");        
      this.day = res[2];
      this.month = res[1];
      this.year = res[0];
      this.editPerfilModal = data.data;
      this.position1Model = this.editPerfilModal.position1Id;
      this.position2Model = this.editPerfilModal.position2Id;
      this.countryModelId = this.editPerfilModal.country['id'];
      this.dominantFootModelId = data.data.dominantFootId;
      this.cityModelId = this.editPerfilModal.city['id'];
      this.stateModelId = this.editPerfilModal.state['id'];
      this.getStates(this.countryModelId);
      this.getCities(this.stateModelId);      
    })
  }


  /**
  * Busca todas as posições
  */
  public getPosition(){
    this.modalService.getPosition().subscribe(data => {
      let first = {label: 'Selecione', id: 0}
      this.positions = data;
      this.positions.unshift(first);
    });
  }


  /**
  * Busca pelo pé dominante
  */
  public getDominatFoot(){
    this.modalService.getDominantFoot().subscribe(data => {
      let first = {label: 'Selecione', id: 0}
      this.dominantFoot = data;
      this.dominantFoot.unshift(first)
    })
  }


  /**
  * Busca todos os paises
  */
  private getCountry(){
    this.modalService.getCountry().subscribe(data => {
      let first = {id: 0, name: 'Selecione'}
      this.countries = data.data;
      this.countries.unshift(first);
    })
  }


  /**
  * Busca os estados a partir da seleção de país
  */
  public getStates(countryId){
    for(let i = 0; i < this.countries.length; i++){
      if(this.countries[i].id == countryId){
        this.states = this.countries[i]['states'];
      }
    }
  }

  /**
  * Busca as cidades a partir da seleção de estados
  */
  public getCities(event){
    for(let i = 0; i < this.states.length; i++){
      if(this.states[i].id == event){
        this.cities = this.states[i]['cities'];
      }
    }
  }


  /**
  * Atualiza Perfil
  */
  updateProfile(){
    this.sendValue.emit('teste')
    this.editPerfilModal.height = this.heigthModel + this.cmModel;
    this.editPerfilModal.birthday = this.day + '-' + this.month + '-' + this.year;
    let obj = {
      birthday: this.editPerfilModal.birthday,
      cityId: this.cityModelId,
      countryId: this.countryModelId ,
      dominantFoot: this.dominantFootModelId,
      height: Number(this.editPerfilModal.height),
      id: this.editPerfilModal.id,
      name: this.editPerfilModal.user['name'],
      lastName: this.editPerfilModal.user['lastName'],
      nickname: this.editPerfilModal.nickname,
      stateId: this.stateModelId,
      position1Id: Number(this.position1Model),
      position2Id: Number(this.position2Model),
      userId: this.editPerfilModal.user['id']        
    }
    this.modalService.updateProfile(obj).subscribe(data => {

      if(data){
        swal(
          "",
          "Perfil atualizado com sucesso!",
          "success"
          );
          this.showModalEdit = false;
        }
      })
    }
  }

edit.perfil.modal.html

<div class="perfil-modal__buttons">
   <button class="btn btn--primary" 
   (click)="updateProfile()">Salvar</button>
</div>

问题是未调用this.sendMessage()函数。我已经尝试放置了一下send(),已经尝试创建一个按钮p测试,而tb却不起作用。但是,如果将此函数放在onInit()中,则会调用它。也就是说,它不适用于点击

1 个答案:

答案 0 :(得分:0)

您应将@Output更新为使用:

@Output() sendValue = new EventEmitter<string>();

这将允许您在事件中发送一个值。