Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

526
Visualizações
Angular - trigger an event based on a variable change

I have a list of items that is set in the service and is called in the ngOnInit():

async ngOnInit(){
   this.items = await this.service.getItems();
}

and this list is rendered using the directive *ngfor.

However, now I need to refresh the items list when there is any change in a variable. So I need an event that runs only when a certain variable (lets called it itemCategories) changes its value lets.

How can I achieve this?

Angular version is 12 and I am new to this

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

fill your data in behaviourSubject then subscribe to it, now your behaviourSubject method will be called whenever you data get changed, here is an example:

I declare my behaviourSubject like these:

  private _resetForm$ = new BehaviorSubject<boolean>(false);


      public set setResetForm(resetStatus: boolean) {
        this._resetForm$.next(resetStatus);
      }
    
      public get resetForm(): Observable<boolean> {
        return this._resetForm$.asObservable();
      }

then I change it here:

  this.setResetForm = true;

now i will get event from here because setResetForm have changed so i will get my event from it:

  ngOnInit(): void {
    this.resetForm.subscribe((res: boolean) => {
      if (res) {
        console.log(res);
      }
    });
  }

good luck!

over 4 years ago · Santiago Trujillo Relatório

0

Based on your short explanation here is a general solution:

wrap your items assignment in a method and call this method when you set the itemCategories value.

async ngOnInit(){
   this.setItems();
}

setItems(){
   this.items = await this.service.getItems();
}

setItemCategories(value){
   this.itemCategories = value;
   this.setItems();
}
over 4 years ago · Santiago Trujillo Relatório

0

You can use the EventEmitter and @Output() to achieve your goal.
Dropdown menu component:

import { Component,  Output, EventEmitter, NgModule } from '@angular/core';
@Component({
  selector: 'app-dropdown',
  template: `
    <div>
      <select [(ngModel)]="selected" (ngModelChange)="onChange($event)">
        <option *ngFor="let category of categories" [value]="category">{{category}}</option>
      </select>
    </div>`
})
export class DropdownComponent {
  @Output() selectedCategory: EventEmitter<string> = new EventEmitter<string>();
  categories = ["All categories", "A", "B", "C"]; //your categories list
  selected: string = "All categories"; //default value 
  constructor() {
  }

  onChange(newvalue): void {
    this.selectedCategory.emit(newvalue);
  }

}  

Here is the other component that will receive the selected value whenever it changes from the dropdown component

import {Component, NgModule} from '@angular/core'
@Component({
  selector: 'app-main',
  template: `
    <div>
      <app-dropdown (selectedCategory)='onChange($event)'></app-dropdown>
    </div>
  `,
})
export class MainComponent {
  selected: string;
  constructor() {
  }

  onChange(category):void {
    this.selected = category;
    //get your items list based on the selected category
  }
}  
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda