Reputation: 6045
I'm trying to see if i can subscribe to a variable of type observable
. when i bind input with [(ngModel)]
the changes don't seem to trigger.
Code:
@Component({
selector: 'alert',
template: '<input type="text" [(ngModel)]="test" />'
})
export class alertComponent {
default:String: 'testValue';
test = Observable.of(this.default).subscribe(x => {
console.log(x); // only logs for first time
});
}
Upvotes: 1
Views: 548
Reputation: 6441
If you want to have your modelvalue as a subscribeable:
@Component({
selector: 'alert',
template: `
<input type="text"
[(ngModel)]="myValue"
(ngModelChange)="myValue$.next($event)"
(blur)="touched$.next($event)"
/>
`
})
export class alertComponent {
default:String: 'testValue';
myValue: string;
myValue$ = new Subject<string>();
touched$ = new Subject<any>();
}
I added the handler on the blur event just to show that you can use this on any type of event.
Another way to operate on any type of event is the rxjs fromEvent method.
In case you never seen the "$" suffix: it is a popular naming convention to add it to anything subscribable.
Upvotes: 0
Reputation: 6015
Observable.of only triggers once. And this is why it is working the first time for you.
If you want to trigger some action you could directly bind it to the ngModelChange event rather than converting it to an observable and subscribing to it ?
You may as well be interested in this question How can I make an input observable?
Upvotes: 0
Reputation: 1325
RxJS 6 and above
import { of } from 'rxjs';
of("testValue").subscribe(x => {
console.log(x)
})
Refer Could not use Observable.of in RxJs 6 and Angular 6
Upvotes: 1