Thursday, October 3, 2019

applying a CSS color to the selection at a dropdown list in HTML versus the individual items within

<select class="noop">
   <option value="" class="noop" selected>Choose</option>
   <option value="foo" class="nice">Foo</option>
   <option value="bar" class="nice">Bar</option>
   <option value="baz" class="nice">Baz</option>
   <option value="qux" class="nice">Qux</option>
</select>

 
 

Alright, herein shall we say that noop gives us a muted grey color because we don't want the form to be submitted without a selection? Come to think of it, maybe bright red would be a better noop color as that says error or not OK instead of just disabled. That seems like better UX to me. I digress. Anyhow nice will just be black. You can basically see how this works above, but what you will need is some JavaScript watching for changes so that noop is set to nice and vice versa as appropriate when a new option is picked at the select tag. At the option tags, the styles will never need to change. Only the style at the select tag changes up via JavaScript. If you jammed #meta (change)="metaChange()" into the select tag in an Angular 7 application you could do something like what follows in the name of swapping out noop for nice and the other way around at the component's TypeScript.

@ViewChild('meta') meta: ElementRef;
public metaChange():void {
   if(this.meta.nativeElement.options[this.meta.nativeElement.selectedIndex].value) {
      this.meta.nativeElement.classList.remove("noop");
      this.meta.nativeElement.classList.add("nice");
   } else {
      this.meta.nativeElement.classList.remove("nice");
      this.meta.nativeElement.classList.add("noop");
   }
}

 
 

Regarding this problem, it may be best to use a .forEach instead of a .changes.subscribe when you have to use ViewChildren instead of a ViewChild. Perhaps an approach to as much could look like:

@ViewChildren('meta') meta: QueryList<ElementRef>
public metaChange():void {
   this.meta.forEach(m => {
      if(m.nativeElement.options[m.nativeElement.selectedIndex].value) {
         m.nativeElement.classList.remove("noop");
         m.nativeElement.classList.add("nice");
      } else {
         m.nativeElement.classList.remove("nice");
         m.nativeElement.classList.add("noop");
      }
   });
}

No comments:

Post a Comment