Q:

Pattern sometimes matched and sometimes not

I've implemented a pattern in angular 5 with the following code in the .ts file for password verification. This suppose to do - support minimum eight characters, at least one uppercase letter, one lowercase letter, one number and one special character. See: Regex for password must contain at least eight characters, at least one number and both lower and uppercase letters and special characters
wcodePattern = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z0-9\d$@$-_!%*?&]{8,20}"; 

I see, when I entered a string in the password text box e.g. Niladri1! its working however, when I entered a string like Nopasss123!!, it shows User name not valid..
Below is the code for angular 5 html:
<div *ngIf="wcode.errors?.pattern">User name not valid.</div> 

I have also tested with the following and it takes string as Noladris which suppose to be invalid. 
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@-_!])[A-Za-z0-9\d@-_!]{8,20}$

Anything I missed?

A:

You need to use
wcodePattern = '^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[@$!%*?&])[A-Za-z0-9@$_!%*?&-]{8,20}$'

Or, since you are using it inside a RegExp constructor, here is a version for use there:
wcodePattern = '^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$_!%*?&-]{8,20}$'

Note:

You must put - at the start/end of the character class to match a literal hyphen, or escape it inside
Backslashes in a string literal must be doubled, else they define escape sequences like \n, \t, etc.
$ must be added at the end of the pattern to "anchor" the match (i.e. match the end of the string to ensure the max char restriction).
[$@$] = [$@]  - there is no need repeating the chars inside a character class.

