0

I'm having a problem in my app when using ngModel on the form with components of Material Design Lite. I was warned that I had to create a directive, as shown in the sample code.

import {Directive, AfterViewChecked, AfterViewInit} from '@angular/core';

declare var componentHandler: any;

@Directive({
  selector: '[mdl]'
})
export class MDL implements AfterViewChecked, AfterViewInit{

  ngAfterViewChecked() {
    if (componentHandler) {
      componentHandler.upgradeAllRegistered();
    }
  }

  ngAfterViewInit(){
    if (componentHandler) {
      console.log('ngAfterViewInit ',componentHandler);
      componentHandler.upgradeAllRegistered();
    }    
  }
}

And use in the component template:

<div mdl class="mdl-layout mdl-js-layout mdl-layout--fixed-header">
...
</div>

Okay, this is working. But when I use [(ngModel)] in my forms, I notice that the directive has no effect on input's. Just remove [(ngModel)] that works again. If I use MDL checkbox for eg.

<label class="mdl-switch mdl-js-switch mdl-js-ripple-effect" for="remember">
    <span class="mdl-switch__label">{{strings.label_remember}}</span>  
    <input name="remember" type="checkbox" id="remember" class="mdl-switch__input" [(ngModel)]="sess.persistent">
</label>

The initial value of the checkbox is not rendered to the user. even if I start the input with the checked property. I do not know if i was clear.

Aderbal Nunes
  • 400
  • 1
  • 6
  • 18
  • The problem is that the MDL switch has [a JS API](https://github.com/google/material-design-lite/blob/mdl-1.x/src/switch/switch.js#L186-L206) that needs to be called for the switch's UI to reflect the `input` element's value. To do that, you need more than a directive. You need a component with a `ControlValueAccessor` implementation - see [this](https://blog.thoughtram.io/angular/2016/07/27/custom-form-controls-in-angular-2.html) for a non-MDL example. – cartant Mar 08 '17 at 21:55
  • I try to use MDL API but, for eg. In MDL switch that object `MaterialSwitch` is undefined. – Aderbal Nunes Mar 09 '17 at 12:30
  • I try `document.querySelector('#ID_OF').MaterialSwitch.on();` but `MaterialSwitch` is undefined. – Aderbal Nunes Mar 09 '17 at 12:32
  • `MaterialSwitch` will be defined on the element with the `mdl-switch` class (the `label` element) once it is upgraded by the `componentHandler`. – cartant Mar 09 '17 at 21:42

0 Answers0