I need to use Observables instead of document.querySelector in Angular 6. My code looks now like this:
onInputChange(result: string) {
const x = document.querySelector('.x') as HTMLElement;
if (result[0] === '4') {
x.style.backgroundColor = '#ffffff';
} else if (result[0] === '5' && result[1] === '5') {
x.style.backgroundColor = '#000000';
} else if (result[0] === '_') {
x.style.backgroundColor = '#AFB8BD';
}
result = result.replace(new RegExp('u', 'g'), 'x');
(<HTMLInputElement>document.getElementById('someInput')).value = result;
}
Actually, the main idea is to change color of the background regarding the first number of "result" input Could someone help me to use Observables? I'm new in Frontend so sorry for this question
Basically I think your issue does not revolves around observables. You wish to change some color of element as a response to some other element action (let's assume on click, because this is not provided in your snippet)
Just use some standard onClick
event listener to set other component style:
<button (click)="onClick()">
<div [class]="classFromController"
and in controller:
onClick() {
if (/* any logic you wish */) {
this.classFromController = 'black';
} else if (/* other logic */) {
this.classFromController = 'white';
}
}
In your css
.black {
backgroundColor = '#ffffff';
}
.white {
backgroundColor = '#000000';
}
Avoid inline styles, because they are considered as terrible coding style and are easy to avoid.
If for some special reason you must use observables, consider using Observable.fromEvent()
as referred below:
http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#static-method-fromEvent