0

estaba pensando en que forma podria disparan un evento en un componete padre en algular pero no se bien cual seria la sintaxis.

Estoy trabajando con formularios y tengo un custon input que estoy uniendo con la interfaz ControlValueAccesor, lo que quisiera hacer es dispara el evento fromTheSon() de el formulario padre

pense hacerlo con una directiva output pero no se como se como hacerlo realmente, se emitir valores pero no como dispara una funcion en el padre.

ESte el componeten padre

import { HttpClient } from '@angular/common/http';
import { Component, OnDestroy, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-registration-form',
  templateUrl: './registration-form.component.html',
  styleUrls: ['./registration-form.component.scss']
})
export class RegistrationFormComponent implements OnInit, OnDestroy {

  dynamicFormArray: any;
  registrationForm!: FormGroup;
  triguerRef: Subscription | any;
  private subscriptions: Subscription[] | any = [];



  constructor(private httpClient: HttpClient, private fb: FormBuilder) { }

  ngOnInit(): void {
    // se incializa el formGroup vacio;
    this.registrationForm = this.fb.group({});
    this.httpClient.get('http://localhost:3000/form').subscribe(data => {
      this.dynamicFormArray = data;
      this.createFormControl();
      this.createFormListener();
      // this.createFormValidators();
    });
  }

  createFormControl(): void {
    // recorre el array para ir creando los controles
    this.dynamicFormArray.forEach((element: any) => {

      if (element.Required) {

        this.registrationForm.addControl(element.ID, new FormControl(element.Value, {
          validators: [Validators.required],
          updateOn: element.Control,
        }));
      } else {
        this.registrationForm.addControl(element.ID, new FormControl(''));
      }
    });

    console.log(this.registrationForm);
  }   


  fromTheSon() {
    console.log('Hellow');
  }

  showStatus(): void {
    if (this.registrationForm.valid) {
      alert('Formulario enviado');
    } else {
      alert('Formulario no valido');
    }
  }    
}

HTML del padre

<div *ngSwitchCase="'custom'">
      <div class="col-md-6 mt-2">
           <app-custom-input [formControlName]="control.ID"></app-custom-input>
        </div>
 </div>

y este el hijo

import { Component, OnInit, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

@Component({
  selector: 'app-custom-input',
  templateUrl: './custom-input.component.html',
  styleUrls: ['./custom-input.component.scss'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => CustomInputComponent),
      multi: true
    }
  ]
})
export class CustomInputComponent implements OnInit, ControlValueAccessor {

  currentValue = 1;
  onChange = (_: any) => { };
  onTouch = () => { };
  isDisabled!: boolean;
  messages!: string |null;

  constructor() { }

  ngOnInit(): void {
  }

  add() {
    if (this.currentValue >= 8) {
      this.showMessage('You cannot have more than 8 Warehouse')
      return;
    }

    this.currentValue = this.currentValue + 1;
    // this.onTouch();
    // this.onChange(this.currentValue);
  }

  sub() {
    if (this.currentValue < 2) {
      this.showMessage('You need at least one');
      this.currentValue = 1;
      return;
    }
    this.currentValue = this.currentValue - 1;
    this.onTouch();
    this.onChange(this.currentValue);
  }

  writeValue(value: number): void {
    if (value) {
      this.currentValue = value;
    }
  }

  // Interface methods
  registerOnChange(fn: any): void {
    this.onChange = fn;
  }

  registerOnTouched(fn: any): void {
    this.onTouch = fn;
  }

  setDisabledState(isDisabled: boolean): void {
    this.isDisabled = isDisabled;
  }

  showMessage(mensaje: string) {
    this.messages = mensaje;
    setTimeout(() => {
      this.messages = null;
    }, 3000);
  }

}
2
  • Para emitir los valores de hijo a padre si usas un output, en el hijo instancias la clase eventChange = EventEmitter<T>();, en el hijo agregas el eventChange.emit() la action (metodo) que disparara el evento, metodo(){ this.evenChange.emit(valor) }, en el componente <custom-input evenChange="fromTheSon($event)"></custom-input>, y ya en el padre, en tu funcion obtienes el evento del hijo fromTheSon(event){...} el 13 ene. 2021 a las 5:30
  • Aca un ejemplo el 13 ene. 2021 a las 5:56

1 respuesta 1

1

Para lograr emitir un evento desde el componente hijo, tienes que crear un evenEmiter de la siguiente manera:

@Output() eventoHijo: EventEmitter<string> = new EventEmitter<string>();

Donde eventoHijo lo vas a declarar en el decorador de llamada en el padre:

<app-componente-hijo (eventoHijo)="changeItem($event)"></app-componente-hijo>

Además debes implementar el método en tu TypeScript:

changeItem($evento){Tu lógica}

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.