Angular 2 Attribute Directive Typescript Example

In this example, we will be creating 2 custom attribute directives in Typescript: –

  • uppercase – namely, convert input into uppercase
  • mask – display view value in a given pattern

Folder

The folder structure and files of this example. The source code is available here.

Angular 2 Attribute Directive Typescript Example folder

uppercase.directive.ts

This directive simply converts user input into uppercase.

mask.directive.ts

This directive takes mask pattern string as an input, converts view value of user input in a format of that pattern. The actual model value is not changed. For example: – use mask=(**) **** **** on a phone number input will be displaying phone number as (03) 1234 1234  while the actual model value is 0312341234 .

app.component.ts

The root component that registers the 2 directives.

app.component.tpl.html

Template of the root component.

boot.ts

index.html

Result

Angular 2 Attribute Directive Typescript Example result

Resources

 


facebooktwittergoogle_plusredditlinkedin

Wayne Hong

Passionate Java full stack developer.
  • Renan Parra

    Please, take this article down, it’s not working right!

    • which angular 2 version you use?

      • Wayne Hong

        Hi Ferri, thanks for trying to help.

    • Wayne Hong

      what do you mean by ‘not working right’? can you please be more specific? i.e. you don’t agree with the example or you have any problem getting the example working?

      • Renan Parra

        Ok, sorry for that, I was in a bad mood, but, i’m using the most recent version AND the problem is the field behavior… for example, if you try to backspace you can’t and others…
        Well, I got the result that I wanted, like this:
        http://pastebin.com/YhH8paMp

        I’m not an expert in JavaScript and Angular but there it is!
        Thanks,

  • Ryan How

    I was so stoked to see your article!. But I’m unable to inject NgModel. No Provider. angular2.0.0-rc1 .They must have changed something, but I can’t figure it out. *Bangs head repeatedly on wall*

    • Wayne Hong

      Hi Ryan,

      Thanks for letting me know. I actually haven’t had a chance to catch up with the latest version yet, sorry about that. But, I had a quick look just now and found that the package name was actually changed in rc1.(Probably starting from rc0)

      so, if you checked the import, you can stop bang your head on wall. :)

      try this (I tried it): –

      import {Directive} from ‘@angular/core’;
      import {NgModel} from ‘@angular/common’;

      see also the bottom line of this page.: https://angular.io/docs/ts/latest/api/common/index/NgModel-directive.html

      Thanks again. And feel free to let me know if you have any questions.

      • Ryan How

        Thanks!. For some reason in my project I needed to add providers:[NgModel] for it to pick it up. Thanks for the Plunker!

  • lfbicalho

    I upgraded this to RC, but the model always get the value with mask, if anyone make it work I would like to see the code.

    • Wayne Hong

      have you checked the comments below? the module names are changed in RC, so you need to change it accordingly it you are using the code from the article, as that was based on beta version. I also created a plunker to demonstrate this. For you convenience, here is the link http://plnkr.co/edit/OmrfNPHnI4toQRVFu0Y1?p=preview

      • lfbicalho

        This one worked, but I was talking about the phone mask directive, the mask work fine for the input, but the model only gets the value with the mask.
        I was using it to format number and dates but I coudn’t get the correct unformated value back in the model.

        Did you make the phone mask work giving the model withou the mask in the RC2?

        • Wayne Hong

          I have updated the plunker with mask directive. do you wanna take another look?

          • lfbicalho

            Your example works fine, there is a problem that if you type one number after it’s complete, the model gets that number but the input doesn’t.

            anyway, I updated your example with ngcontrol tag and then I get an error

            http://plnkr.co/edit/6Pv0Yj2pVeAdDEUlJOVo

            No provider for NgModel!

          • Wayne Hong

            just inject ngControl instead of ngModel. see http://plnkr.co/edit/3T2tqq?p=preview

          • lfbicalho

            Now it’s almost ok, I could reproduce your work, but I got two little issues:

            1) my model is a number, but it’s stored in the model as string.

            2) if I try to use the FormGroup.value to get the value from the model, it returns the value from the view (with mask).

          • lfbicalho

            I Solved the first problem, it was my mistake, the second one is still happening

            http://plnkr.co/edit/KXtNOPCkCD6kiDgkbAuO?p=preview

          • Wayne Hong

            the problem was that, the model value change didn’t send to form control. I haven’t looked into that part yet, so I don’t know whether what’s intended or not. but in order to get what you want, you can add below line in your update() method.

            this.model.control.updateValue(this.modelValue);

            just right before setting view value
            this.model.valueAccessor.writeValue(this.viewValue);

            this should work. http://plnkr.co/edit/ZCaTPMjvFLf32BHFfb59?p=preview

          • lfbicalho

            I had to change the code, I had an compilation error

            private update() {
            this.modelValue = this.getModelValue();
            this.viewValue = this.format(this.modelValue);
            this.model.viewToModelUpdate(this.modelValue);
            (this.model.control).updateValue(this.modelValue);
            this.model.valueAccessor.writeValue(this.viewValue);
            }

            Is there a reason for the order you mentioned? I mean, if they change different parts of the model, it should work fine in any order, unless the updateValue or the viewToModelUpdate also update de viewValue.

            For me it would be much better if I could see a big class diagram of all classes.

            Thanks for the huge help.

  • vijayaragavendiran raja

    @@disqus_agq1rVMmFA:disqus Instead of binding the string in the mask attribute. I want to bind the expression. Based on the expression the mask string changes.
    Something like in HTML attribute [mask]=”Obj.Format==”y”?’***-***-*****’:null.
    Can we have like that in your code?