Angular2 Forms Validation Error messages
<p>I am new to Angular and JavaScript overall, I'm trying to add messages when user input is wrong using the Materialize library (the data-error attribute). So my html component looks like this:</p>

<pre><code>            &lt;input
                    type="text"
                    id="username"
                    formControlName="username"
                    [class.valid]="username?.valid &amp;&amp; username.dirty"
                    [class.invalid]="!username?.valid &amp;&amp; username.dirty &amp;&amp; !username.pending"
            &gt;
            &lt;label for="username"
                   data-error="ERROR_MESSAGE" // &lt;-- this is what I need to work
            &gt;Username&lt;/label&gt;
</code></pre>

<p>I want to change the data-error attribute depending on the error present. Right now it will print "ERROR_MESSAGE" on any error present. I tried writing a function and binding it with [attr.data-error] like this:</p>

<pre><code>    displayUsernameErrorMessage() {
    let message = '';
    let usernameError = this.username.errors;
    if(usernameError.pattern){
        message = "Invalid Username"
        console.log(usernameError);
    }
    else {
        return null;
    }
}
</code></pre>

<p>I think I'm doing a really bad job with this, the function logs like 10 times in the console and it's a poor solution. Any ideas on how to make it work better are greatly appreciated!</p>

<p><strong>EDIT 1:</strong> Additional info is that I want to display different messages depending on the error. So if I get an error from the Validator.pattern - I want the message to be something like "Invalid username" or if it's from Validators.required - "Please insert a username", something like that.</p>