0

I want to add a class to the container when the input field has a focus or when the dropdown component gets focus or is clicked. On unfocus the class must be removed.

The input container must get the class 'active' when the input field or the dropdownComponent has focus or is clicked. For the input field I added ng-focus and ng-blur, which works.

But ng-focus and ng-blur doesn't work on a included component. I wrap the component in a div container, but this time ng-blur didn't work.

The code:

<div class="input-container" ng-class="{'active': focus}">
    <dropdownComponent ng-if="dropdownButton" element="dropdownElement">
    </dropdownComponent>

    <input type="text"
        id="{{inputElement.key}}"
        class="form-control"
        placeholder="{{inputElement.placeholder}}"
        ng-model="inputElement.values[0]"
        ng-readonly="{{::inputElement.readonly}}"
        ng-focus="focus=true"
        ng-blur="focus=false;"
        ng-required="{{::inputElement.required}}"
        novalidate />
</div>

Is there an option to add something like

<dropdownComponent ng-if="dropdownButton" 
                   ng-focus="focus=true"
                   ng-blur="focus=false"
                   element="dropdownElement">
</dropdownComponent>

Directly adding ng-focus and ng-blur to the component didn't work.

focus-within with css works, but this doesn't support older browsers.

georgeawg
  • 48,608
  • 13
  • 72
  • 95
can
  • 214
  • 2
  • 14

1 Answers1

1

It doesn’t work for the component because the focus and blur events work only for the form elements. For the component with the dropdown, you may use mouseenter and mouseleave events. And use the click event when the component gets clicked.

Updated:

<div class="input-container" ng-class="{'active': toggleClass}">
    <dropdownComponent ng-if="dropdownButton" ng-click="toggleClass = !toggleClass" element="dropdownElement"></dropdownComponent>
</div>

In your .js file set the variable as $scope.toggleClass = false;

REMOVE CLASS ONCLICK OUTSIDE:

var element = document.querySelector('.input-container');    
$window.onclick = function(event) {
        if(event.target !== element && element.classList.contains('active')) {
            $scope.toggleClass = false; 
        }
    }
Angela Amarapala
  • 1,002
  • 10
  • 26