0

Let's say I want to implement and use the following ts module. It's just a basic validator that validates a first name:

export namespace Validators
{
    export class NameValidator
    {
        constructor()
        {
        }

        FirstNameIsValid(firstName: string)
        {
            return firstName.length < 20;
        }
    }
}

What would be the correct way for me to implement the module above? Also, what would be the correct way for me to reference and use this module from my ng2 component? The following import statement doesn't work:

import { Validators.NameValidator } from './modules/name-validator';
6
  • nope that doesn't work Commented Aug 10, 2017 at 0:02
  • possible duplicate of stackoverflow.com/a/34864779/7176268 . The gist of it is with angular there isn't a need for namespaces since we use a module loader to import only needed modules. Commented Aug 10, 2017 at 0:42
  • @LLai - interesting point. I took another look at an ng2 component that I created based off examples provided at angular.io and it doesn't have a namespace, so it looks like namespaces are not used in ng2. thanks for the insight! Commented Aug 10, 2017 at 16:15
  • np! as a side note, if you were to have 2 files with exports of the same name, you can import them with aliases import {NameValidator as AliasName} from "./name-validator"; (developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…) Commented Aug 10, 2017 at 16:42
  • thanks! as I was developing my component, I recognized the need for what, in the js world, would be called a "module." I googled and found the concept of "typescript modules." however, in the context of an ng2 app, if I have a standalone ts class which does not map to an ng2 architecture type, should I refer to that as a supporting "module" or supporting "class" since the "class" keyword is used explicitly? Commented Aug 10, 2017 at 17:13

1 Answer 1

0

The way I have done it in the past is to create a module

module Formatter{

  export class SsnFormatter {
        ssn: string;
        constructor(unformattedSsn: string) {
            this.ssn = unformattedSsn.replace(/(\d{3})(\d{2})(\d{4})/, '$1-$2-$3');
        }
        formatSsn() {
            return this.ssn;    
        }
    }
}

Then within the other typescript files call it as

let f = new Formatter.SsnFormatter('111111111');
console.log(f);

As long as your class is within the same module namespace you should be able to reference it directly.

This was from an angular 1.x project but the version of TS or angular should not matter this is typescript communicating between modules.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.