Changing color of tag-input dynamically angular2

857 Views Asked by At

I want to send invitation email to the users from UI. I need to type multiple email ids of those users which are not already part of our system. I'm using angular2's tag-input for it. Everything is working fine except some validation. After typing email, I'm checking whether user is already exist in the system or not. If the user is exist, then I want that email tag to be highlighted as red. So at the end all the emails which are already present in the system, should have red color for their tags.

Following is my component:

  public validateEmail(item: any): string {
    if(item.includes("@") && item.includes(".")) {
      return `${item}`;
    }
  }

  public onAdd(item: any) {
    this.userService.getUserByEmail(item).then(
      (response: any) => {
        this.users = response;
        if(this.users.length === 0) {
          this.canSend = true;
          this.emails.push(item);
        } else {
          this.errorItem = item;
          this.isError = true
          this.canSend = false;  
        }
      }
    ).catch(
      (error: any) => console.log(error)
    )    
  }

  public onRemove(item: any) {
    let index = this.emails.indexOf(item);
    this.emails.splice(index, 1);
    if(item === this.errorItem)
    {
      this.isError = false;
      this.errorItem = ""
      this.canSend = true;
    }
  }

Below is HTML code:

<md-card class="default-card">
  <h2>{{ 'invitation' | translate}}</h2>
</md-card>

<md-card class="default-card">
  <div>
    <md-hint class="error-hint">
      <span *ngIf = "isError">{{'Please remove email: ' | translate}}{{errorItem}}</span>
    </md-hint>
    <tag-input [ngModel]="emails"
               separatorKeys="[32]"
               (onRemove)="onRemove($event)"
                 (onAdd)="onAdd($event)"
               [transform]="validateEmail"
               [secondaryPlaceholder] ="('Enter email ids' | translate)"
               [placeholder]="('+ Email')">
    </tag-input>
  </div>
</md-card>
<div class="send-invite-wrapper">
  <div class="fill-send-invite"></div>
  <button md-raised-button color="primary" class="save" [disabled] = "!canSend || isError"
          (click)="sendInvite()">{{'send invitation' | translate}}
  </button>
</div>
1

There are 1 best solutions below

0
On

you can use the [divideColor] property to set color dynamically

<md-input-container [dividerColor] =(!yourform.controls['fieldname'].valid && yourform.controls['fieldname'].touched) ? 'warn' : 'primary'">
    <input mdInput placeholder="fieldname >
</md-input-container>

this will dynamically change the color of the field to red from default primary color