Angular EventEmitter does not work at times

Discussão em 'Angular' iniciado por Gerard, Abril 8, 2025.

  1. Gerard

    Gerard Guest

    I'm having trouble with Angular's EventEmitter.

    I don't know why, but when I create an element, the EventEmitter works correctly, but when I try to update an element, it doesn't works.

    I have declared the eventemitter such that:

    @Output() public updatedIngredient = new EventEmitter<boolean>();


    The function to create an element is as follows:

    public async createIngredient(): Promise<void> {
    try {
    if (this.ingredientForm.valid) {
    const ingredient: Ingredient = {
    name: this.ingredientForm.get('ingredientName')?.value,
    description: this.ingredientForm.get('ingredientDesc')?.value,
    type: this.ingredientForm.get('ingredientType')?.value,
    };

    await this.ingredientService.createIngredient(ingredient);

    this.closeIngredientModal(true);
    }
    } catch (error: any) {
    if (error.error.code === 'DUPLICATE_KEY') {
    this.ingredientNameError = this.translateService.instant(
    'APPS.YOUR_CHEF.INGREDIENT.error_existing_ingredient'
    );
    }
    throw error;
    }
    }


    The function to update an element is as follows:

    public async updateIngredient(): Promise<void> {
    try {
    if (this.ingredientForm.valid) {
    const ingredientData: Partial<Ingredient> = {
    name: this.ingredientForm.get('ingredientName')?.value,
    description: this.ingredientForm.get('ingredientDesc')?.value,
    type: this.ingredientForm.get('ingredientType')?.value,
    };

    await this.ingredientService.updateIngredientById(
    this.ingredient?._id || '',
    ingredientData
    );
    this.closeIngredientModal(true);
    }
    } catch (error) {
    throw error;
    }
    }


    Both functions go through closeIngredientModal, which is responsible for both closing the creation/update modal of the element, and emitting an event indicating whether the element has been created or updated. This is the implementation of closeIngredientModal

    public closeIngredientModal(createdOrUpdated: boolean) {
    this.openedCreateModal = false;
    this.ingredientNameError = '';

    if (this.ingredient) this.initializeUpdateForm();
    else this.initializeCreateForm();

    this.updatedIngredient.emit(createdOrUpdated);
    }


    As you can see in this function, an event is emitted to the parent when an element has been created or updated, but I don't know why, when I update an element, this event is not emitted.

    I have verified that createdOrUpdated is pulled both when the item is created and when it is updated and in both cases it is true. That's why I don't undertand why it doesn't work in EventEmitter when I update an element.

    Does anyone know why the event emitter doesn't work in the case I mentioned?

    Continue reading...

Compartilhe esta Página