Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

530
Views
Angular: activa un evento basado en un cambio de variable

Tengo una lista de elementos que se establece en el servicio y se llama en el ngOnInit():

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

y esta lista se representa usando la directiva *ngfor.

Sin embargo, ahora necesito actualizar la lista de elementos cuando hay algún cambio en una variable. Entonces, necesito un evento que se ejecute solo cuando una determinada variable (vamos a llamarla itemCategories ) cambia su valor.

¿Cómo puedo conseguir esto?

La versión angular es 12 y soy nuevo en esto.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

complete sus datos en BehaviorSubject y luego suscríbase, ahora se llamará a su método BehaviorSubject cada vez que cambien sus datos, aquí hay un ejemplo:

Declaro mi asunto de comportamiento como estos:

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

entonces lo cambio aquí:

 this.setResetForm = true;

ahora obtendré un evento desde aquí porque setResetForm ha cambiado, así que obtendré mi evento de él:

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

¡buena suerte!

over 4 years ago · Santiago Trujillo Report

0

Según su breve explicación, aquí hay una solución general:

envuelva su asignación de elementos en un método y llame a este método cuando establezca el valor de itemCategories .

 async ngOnInit(){ this.setItems(); } setItems(){ this.items = await this.service.getItems(); } setItemCategories(value){ this.itemCategories = value; this.setItems(); }
over 4 years ago · Santiago Trujillo Report

0

Puede usar EventEmitter y @Output() para lograr su objetivo.
Componente del menú desplegable:

 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); } }

Aquí está el otro componente que recibirá el valor seleccionado cada vez que cambie del componente desplegable

 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!