1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

How to force Angular to update the signals?

Discussão em 'Angular' iniciado por suer231232131133, Maio 14, 2025.

  1. I have a service:

    import { Injectable, signal } from '@angular/core';

    @Injectable({
    providedIn: 'root',
    })
    export class WeatherCardsService {
    constructor() {}

    selectedRegion = signal('Signal Region');
    selectedCity = signal('Signal City');

    mainCities: any[] = [
    {
    city: 'Puerto rico',
    temperature: 25,
    desc: 'Take sunglasses and use SPF cream.',
    url: '../../../../../assets/weather/sunny.jpg',
    },
    {
    city: 'Wrocław',
    temperature: 13,
    desc: 'First days of spring are coming.',
    url: '../../../../../assets/weather/autumnly.jpg',
    },
    {
    city: 'Yakutsk',
    temperature: -10,
    desc: 'Wear a thick jacket and gloves.',
    url: '../../../../../assets/weather/snowy.jpg',
    },
    ];
    getCards() {
    return this.mainCities;
    }

    getCitiesArray() {
    return this.citiesArrays;
    }

    getRegionsArray() {
    return this.regionArrays;
    }

    setSelectedRegion(region: string) {
    this.selectedRegion.set(region);
    console.log(this.selectedRegion);
    }
    setSelectedCity(city: string) {
    this.selectedCity.set(city);
    }
    getSelectedRegion() {
    return this.selectedRegion();
    }
    getSelectedCity() {
    return this.selectedCity();
    }

    citiesArrays: string[] = ['Wrocław', 'New York', 'Tokyo'];
    regionArrays: string[] = [
    'Europe',
    'Asia',
    'North America',
    'South America',
    'Oceania',
    'Africa',
    ];

    }


    component.ts

    constructor(private weatherCardsService: WeatherCardsService) {}
    test: string = 'test';
    selectedCityFromSignal = this.weatherCardsService.getSelectedCity();
    selectedRegionFromSignal = this.weatherCardsService.getSelectedRegion();
    citiesArrays: string[] = [];
    regionArrays: string[] = [];
    getCities() {
    this.citiesArrays = this.weatherCardsService.getCitiesArray();
    }
    getRegions() {
    this.regionArrays = this.weatherCardsService.getRegionsArray();
    }


    and html:

    {{ selectedCityFromSignal }}
    {{ selectedRegionFromSignal }}


    the value chages are called in form:

    (change)="setCity(city.value)"


    setCity(city: string) {
    console.log(city);
    this.weatherCardsService.setSelectedCity(city);
    }


    the problem is that the console.logs are correct but the value in the html is always inital and never got updated. How to force Angular to update the signals and keep the values always up to date as singals in service are changed?

    Continue reading...

Compartilhe esta Página