angularangular-translatecustom-attribute

Angular translate on custom attributes


I have a switch widget which uses custom data attribute value to label itself.

.switch.switch-text .switch-label::before {
  right: 1px;
  color: #c2cfd6;
  content: attr(data-hide);
  }
  
  .switch.switch-text .switch-label::after {
  left: 1px;
  color: #c2cfd6;
  content: attr(data-show);
  opacity: 0;
}

.switch.switch-text .switch-input:checked ~ .switch-label::before {
  opacity: 0;
}

.switch.switch-text .switch-input:checked ~ .switch-label::after {
  opacity: 1;
}
<label class="switch switch-text switch-pill switch-primary">
                            <input type="checkbox" class="switch-input" checked>
                            <span class="switch-label" attr.data-show="{{GLOBALS.ACTIONS.SHOW | translate}}" attr.data-hide="{{GLOBALS.ACTIONS.HIDE | translate}}"></span>
                            <span class="switch-handle"></span>
                        </label>

But it just does not work. I have looked at different answers relating to similar problem but some says it works some says it doesn't. If I user without attr. in front I get a binding error anyway since it does not recognise the attribute.

How can I translate the value of custom attribute using angular translate?


Solution

  • You just have a typo in your template. Your have to use a one way data binding syntax to update attributes "data-show" with the translated value. If you omit the bracket then you just create a static "attr.data-show" attribute whom value is "{{GLOBALS.ACTIONS.SHOW | translate}}"

    Your code produces :

    <span class="switch-label" attr.data-show="{{GLOBALS.ACTIONS.SHOW | translate}}" attr.data-hide="{{GLOBALS.ACTIONS.HIDE | translate}}"></span>
    

    The corrected template syntax is :

      <label class="switch switch-text switch-pill switch-primary">
            <input type="checkbox" class="switch-input" checked>
            <span class="switch-label" [attr.data-show]="'GLOBALS.ACTIONS.SHOW' | translate" [attr.data-hide]="'GLOBALS.ACTIONS.HIDE' | translate"></span>
            <span class="switch-handle"></span>
       </label>