1

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

Julie R
  • 35
  • 7

2 Answers2

1

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

Tomas
  • 3,269
  • 3
  • 29
  • 48
  • @JulieR good to know, but as I already mention, at least from code you provided, observables really seems not needed in your case. Anyway, glad I was able to help – Tomas Nov 08 '18 at 12:16
0

The problem to your question is, that we don't really know what your components are

Angular provides you two ways to interact with component and events

const yourEvent = fromEvent(button, 'click');

Example:

    <input type="text" #comp (keyup)="onChange(comp.value)"/>
Jonathan Stellwag
  • 3,843
  • 4
  • 25
  • 50
  • Thank you! Actually, the main idea is to change color of the
    background regarding the first number of "result" input
    – Julie R Nov 08 '18 at 08:50
  • 1
    @JulieR I think you mean to have an observable on the event of change in 'result' input... take a look at https://www.learnrxjs.io/operators/creation/fromevent.html – Akber Iqbal Nov 08 '18 at 09:23
  • If your component doesn't provide an Angular event you can use fromEvent() true :) Well done sir. I will add it to the answer if it's ok for you? – Jonathan Stellwag Nov 08 '18 at 09:45