0

I want to use JavaScript code in an Angular application. I tried this:

export class MerchantNewComponent extends FormBaseComponent {

  constructor(private merchantService: MerchantService,
              private router: Router) {
    super();
  }

  function randomString() {
    var length = 40;
    var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    var result = '';
    for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
    return result;
  }
}

But I get this error:

enter image description here

Does anybody know how I can use this JavaScript code in an Angular application?

2
  • Please post your errors as text. Commented Feb 18, 2019 at 13:51
  • One option is to declare the function outside of the class and use it in the class. Commented Feb 19, 2019 at 19:01

2 Answers 2

3

Use the TypeScript syntax to declare a method in a class:

export class MerchantNewComponent extends FormBaseComponent {

  getRandomStr(): string {
    // ...
  }
}

Notes

  1. It's recommended to add the return type of the function next to the function declaration.
  2. Consider renaming the function to be more descriptive and to denote that it returns a value. (like what I've done above randomString becomes getRandomStr - this clarifies what exactly the function does)

For more info, check out the TypeScript handbook on classes


EDIT: To specify an argument that should be passed into a method, see below:

getRandomStr(randomLength: number): string {
  // Do something w/ the randomLength variable
  console.log(randomLength);
  // ...
}
Sign up to request clarification or add additional context in comments.

2 Comments

What about the vars into the method?
You can specify an argument in between the brackets.
1

should be public randomString instead of function randomString

function can be used outside the class, if it is inside, then it is a method of the class, not a function anymore.

If you use it inside the component, you can call it by using this.randomString() or randomString() in the template

You can also use getter public get randomString() {...} then when you use it, you only need to call it as this.randomString

1 Comment

Anything else to change?

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.