ionic-framework icon indicating copy to clipboard operation
ionic-framework copied to clipboard

Custom Value Accessors with ion-input (Ionic 2)

Open endoooo opened this issue 10 years ago • 29 comments

hey guys!

I'm having problem using a custom value accessor with ion-input. what I'm trying to do is to format an input text field while the user is typing, to enhance the user experience, like this: 12345678900a => 123.456.789-00 (it removes all the non-digit characters and apply the dots and dash).

to achieve this, I've created a custom value accessor as discussed in https://github.com/angular/angular/issues/6174.

the problem is that when I use the custom directive with a "pure" input, the value saved to ngFormControl is correct, but when I use the same directive in a ion-input, the value passed to the ngFormControl is not the one that the user is actually seeing, but the value before the formatting (for instance, if the user types 123a, what he sees in the input is 123, but the value in the model is 123a).

thank you and congrats for the outstanding work with Ionic 2!


the code (excerpts) from the custom value accessor, form component and form template:

custom value accessor

@Directive ({
  selector: '[agl-id-num]',
  host: {
    '(input)': 'doOnChange($event.target)',
    '(blur)': 'doOnBlur($event.target)'
  },
  bindings: [ CUSTOM_VALUE_ACCESSOR ]
})
export class IdNumAccessor extends DefaultValueAccessor {

  constructor(_renderer: Renderer, _elementRef: ElementRef) {
    super(_renderer, _elementRef);
  }

  writeValue(value:any):void {
    if (value!=null) {
      super.writeValue(value);
    }
  }

  doOnChange(elt) {
    // prevent user to input non-digit characters while typing
    // and limit user input to 11 characters
    let val = elt.value
      .replace(/\D/g, '')
      .substring(0,11);

    elt.value = val; // this is what changes the input value as user types

    this.onChange(val); // this is what saves the value to the model
  }

  doOnBlur(elt) {
    // format field on blur only
    let val = elt.value;
    if (val.length === 11) {
      elt.value = val.replace(/^(\d{3})(\d{3})(\d{3})(\d{2})/, '$1.$2.$3-$4');
    }
  }
}

form component

@Component({
  selector: 'agl-client-register-form',
  templateUrl: 'build/components/clients/client-register-form/client-register-form.component.html',
  directives: [ FORM_DIRECTIVES, IdNumAccessor ]
})
export class ClientRegisterFormComponent implements OnInit {
  form: ControlGroup;  

  @Output() onFormSubmit = new EventEmitter();
  @Input() initialValues;

  constructor(
    private fb: FormBuilder) {}

  ngOnInit() {
    console.log(this.initialValues);

    this.form = this.fb.group({  
      'name':               [this.initialValues.name, Validators.required],
      'idNum':              [this.initialValues.idNum, Validators.required],
      'idNumTest':          [this.initialValues.idNum, Validators.required],
      'email':              [this.initialValues.email],
      'celphone':           [this.initialValues.celphone],
      'sendBoletoToMyself': [this.initialValues.sendBoletoToMyself]
    });
  }

  onSubmit():void {
    console.log(this.form.value);
  }
}

form template

<form novalidate
    [ngFormModel]="form"
    (ngSubmit)="onSubmit()">
    <ion-list>
        <!-- using with "pure" input -->
        <input
            agl-id-num
            type="tel"
            [ngFormControl]="form.controls['idNumTest']"
            required />
        <ion-item>
            <ion-label floating>Id Num*</ion-label>
            <!-- using with ion-input (described problem) -->
            <ion-input
                agl-id-num
                type="tel"
                [ngFormControl]="form.controls['idNum']"
                required>
            </ion-input>
        </ion-item>
    </ion-list>
    <div padding>
        <button block type="submit">Register</button>
    </div>
</form>

using Ionic 2.0.0-beta.6

endoooo avatar May 19 '16 16:05 endoooo

Hello! Thanks for opening an issue with us! Would you mind making a plunker that demonstrates this issue please?

jgw96 avatar May 20 '16 19:05 jgw96

sure! there it is: http://embed.plnkr.co/b2rvq3uHcrxpmzTZ23f1/

I've applied the custom num accessor to both inputs (the ion one and the "pure" one). note that in the ion-input, when I type a non digit character it is reflected in the form.value, but in the non-ion input it doesn't happen.

endoooo avatar May 23 '16 04:05 endoooo

This might be related to https://github.com/angular/angular/issues/5328. Since upgrading to Ionic 2.0.0-beta.7 I'm struggling with the issue that Ionic and Angular form handling seems to be constantly out of sync by one event.

Edit: My issue only occurs when using ChangeDetectionStrategy.OnPush though.

robertdp avatar May 25 '16 02:05 robertdp

@robertdp hum... it could be somehow related. thanks for referencing the issue!

in my case, what seems to be happening is that the DefaultValueAccessor is conflicting with my IdNumAccessor in the ion-input: the onChange event exists in both accessors, but only when used in an ion-input (with html input this doesn't happen, as shown in the plunker) it looks like the onChange in the IdNumAccessor is not being triggered and therefore the related model is binded to the value before the element.value change that happens in IdNumAccessor.

endoooo avatar May 25 '16 20:05 endoooo

Yeah, the similarities were superficial. The deeper I went into the issue with change detection the less it seemed to apply to this issue.

robertdp avatar May 25 '16 23:05 robertdp

any news on this issue?

(ps: upgrading to the current beta 8 does not help on this...)

endoooo avatar Jun 13 '16 23:06 endoooo

This is still a problem in 2.0.0-beta.10

assisrafael avatar Jun 28 '16 22:06 assisrafael

Hi @endoooo, any news on this issue? I have the same problem with ionic 2 RC-0

Regards

jbgomez21 avatar Oct 16 '16 18:10 jbgomez21

hi @jbgomez21!

i think it's still an issue... unfortunately.

in the end we used HTML inputs and styled them like ion-inputs. it's not the perfect solution and it was not what we really wanted (all the MD animations were gone), but it worked.

endoooo avatar Oct 17 '16 21:10 endoooo

Hi @endoooo It is not an ionic 2 problem I have created a plunker example about this problem. http://embed.plnkr.co/lWpjyCwL0l2r06u1BI0a/ (Running on Chrome)

with 16 digits work fine, but with 17 digits the input label show 1 extra character!

I think that I have a conceptual problem about what happened. Can someone explain it to me please?

jbgomez21 avatar Oct 18 '16 01:10 jbgomez21

@endoooo @jbgomez21 You can pass the FormControl inside the directive and call setValue manually. This way the FromGroup will be updated

NelsonBrandao avatar Oct 18 '16 14:10 NelsonBrandao

@jbgomez21 I've made some changes in your plunker, and now it's working as it should: https://embed.plnkr.co/0vfCj6AyjfQgLGxDtDpj/

there were some problems with your implementation:

  • the value accessor (which is a @Directive) was mixed with the input @Component. roughly speaking, the value accessor cares about which value should be presented in the component and how it should be saved in its model, and the input component cares about the user interface.
  • your model was a primitive (string). the problem with this approach is that primitives values are passed by value and not by reference in javascript, which can cause some problems when you need to traverse the data across multiple components (3+) in the component tree.
  • the way your were passing @Input values to the child components were a bit messy (no []s).

there were some other changes I've made. check the code and see if you can understand them.

@NelsonBrandao thanks for the tip. I didn't test it (so it may work), but I don't think passing FormControl inside the value accessor is a clean solution. the point of using the value accessor's onChange is exactly to reflect the value to the control model without referencing the FormControl directly, isn't it?

endoooo avatar Oct 18 '16 17:10 endoooo

@endoooo Thank you very much for your corrections. They have been very helpful for me and surely be for other people.

Regards!

jbgomez21 avatar Oct 18 '16 18:10 jbgomez21

@endooo Yup, not the best solution, just a quick fix until there is better one that works on ion-input

NelsonBrandao avatar Oct 18 '16 20:10 NelsonBrandao

Hi @endoooo

This Directive work for me with javascript<ion-input>. Please, look at and give me your comment


import { Directive, ElementRef, Renderer, OnInit } from '@angular/core';
import { DefaultValueAccessor, NgControl } from '@angular/forms';

declare var VMasker: any;

const CardMaskLength: number = 16;
const Mask: string = '9999-9999-9999-9999';

@Directive({
  selector: '[card-mask][ngModel]', // Attribute selector
  providers: [DefaultValueAccessor]
})
export class CardMask implements OnInit {
  constructor(
    private renderer: Renderer,
    private elementRef: ElementRef, private model: NgControl) { }


  writeValue(value: any): void {
    // Write to view        
    if (value !== null && value !== undefined) {

      value = VMasker.toPattern(value, Mask);

      this.model.valueAccessor.writeValue(value);
      this.renderer.setElementProperty(this.elementRef.nativeElement.firstChild, 'value', value);    
    }
  }

  valueChange(value) {
    // prevent user to input non-digit characters while typing
    // and limit user input to CardMaskLength characters         
    let val = value.replace(/\D/g, '');
    val = val.substring(0, CardMaskLength);    

    //write formatted to control view
    this.writeValue(val);

    this.model.viewToModelUpdate(val);    
  }

  ngOnInit() {
    this.model.valueChanges.subscribe((value : any) => {
        this.valueChange(value);
    });
  }
}

then, I can use it

<ion-input type="text" placeholder="1234 5678 9012 3456" card-mask [(ngModel)]="_model.cardNumber"></ion-input>

<p>{{_model.cardNumber}}</p>

I do not know why I have to put both statements, but it works. If I remove one does not work properly.

      this.model.valueAccessor.writeValue(value);
      this.renderer.setElementProperty(this.elementRef.nativeElement.firstChild, 'value', value);    

Can someone explain it to me please?

sorry for my bad english :-)

jbgomez21 avatar Oct 19 '16 07:10 jbgomez21

@jbgomez21 maybe I'm wrong (because I don't have a deep knowledge about what ng2 is doing behind the scenes), but I think that what you're doing here is imitating (in a simpler way) the implementation of the custom value accessor.

it should work for what you need, but I don't know for sure what are the side effects of this implementation. I have three main points of concern with your directive:

  • you are manually implementing some things that should happen "automatically" (or in different ways), like the valueChanges subscription as a way to trigger the this.valueChange(value) and the this.model.viewToModelUpdate(val), for instance. my concern here is that if Angular use those events to trigger another ones, it will start to happen twice
  • if I figured it out right, the this.model.valueAccessor.writeValue(value) may be triggering the DefaultValueAccessor writeValue method, which is:
writeValue(value: any): void {
  var normalizedValue = isBlank(value) ? '' : value;
  this._renderer.setElementProperty(this._elementRef.nativeElement, 'value', normalizedValue);
}

this doesn't feel right, right? 😄 now, in order to figure out why this only works when you use both writeValue and setElementProperty, I'd need to run some tests, but I don't have the time for doing it now... 😶

  • and last but not least, how will it work with FormControl and FormGroup validators?

what do you think?

if anyone else could express your thoughts about this topic, it would be great!

endoooo avatar Oct 19 '16 12:10 endoooo

@endoooo Yes, It works with FormControl and FormGroup validators.

I am agree that it isn't the best solution, but my intent was someone explain to me why this works :-) I don't know why with ion-input doesn't work @Directive that implements CustomValueAccessor. :-(

Regards!

jbgomez21 avatar Oct 19 '16 23:10 jbgomez21

@endoooo and @jbgomez21, thanks for your effort, but how can I solve this Can't bind to 'mask' since it isn't a known property of 'ion-input'. :sob:

<ion-input [mask] placeholder="Manuálne zadanie kódu"
					formControlName="serialNumber">
				</ion-input>

luckylooke avatar Jul 25 '17 12:07 luckylooke

Hi @luckylooke Please give me more detail about what are you doing. If you have a "mask" @Directive then sintaxis is <ion-input mask placeholder="..."> </ion-input>

[mask] refer to input property that ion-input doesn't have

Regards.

jbgomez21 avatar Jul 25 '17 13:07 jbgomez21

mask directive is copy of your card-mask and I wanted to be input so I can pass mask as parameter like so: <ion-input [mask]="[0-9]{6}-[0-9]{6}" placeholder="..."> </ion-input> but it is true that mask attribute directive without [] is accepted by ionic input. Thanks for hint, maybe this will help me go forward 🤔

luckylooke avatar Jul 27 '17 19:07 luckylooke