Reputation: 311
I'm starting to work with signals in newer versions of Angular. To be specific, I am working with a signal and an effect, I have a component with an input, the effect detects the input changes and works with the resulting chain of the input. The problem is that the Effect runs during initialization, after that it does nothing, it doesn't matter if new characters are typed, when the page reloads, the effect runs every time the user types a new character in the input, That is, it detects the change correctly on the input. The thing is, I don't know why it works fine only after reloading the page.
Component:
export class ViewComponent {
private _sharedSignals = inject(SharedSignals)
constructor() {
effect(() => {
const word = this._sharedSignals.getWord();
console.log("WORD: ", word);
// more logic...
});
}
}
Service:
@Injectable({
providedIn: 'root'
})
export class SharedSignals {
word = signal<string>('');
constructor() { }
setSearchTerm(value: any) {
this.searchTerm.set(value);
}
getSearchTerm() {
return this.searchTerm();
}
}
I'm pretty new to signals so any help is appreciated.
Upvotes: 1
Views: 100
Reputation: 58071
Maybe it's just a HTML configuration miss, as far I can see it works fine. Here is a working example using [(ngModel)]
.
import { Component, Injectable, effect, inject, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';
@Injectable({
providedIn: 'root'
})
export class SharedSignals {
word = signal<string>('');
constructor() { }
setSearchTerm(value: any) {
this.word.set(value);
}
getSearchTerm() {
return this.word();
}
}
@Component({
selector: 'app-root',
standalone: true,
imports: [FormsModule],
template: `
<input [(ngModel)]="_sharedSignals.word"/>
<br/> {{_sharedSignals.word()}}
`,
})
export class App {
public _sharedSignals = inject(SharedSignals)
constructor() {
effect(() => {
const word = this._sharedSignals.getSearchTerm();
console.log("WORD: ", word);
// more logic...
});
}
}
bootstrapApplication(App);
Upvotes: 0