0

I am using Angular 6 with Angular Material 6. I want to required the mat-chip field. When i input mat-chip field then the save button will be enable otherwise will be disabled. The input field is required but can not able to require the mat-chip field. Please help me to find the solution. Thanks.

My sample code link here: stackblitz demo

monir tuhin
  • 441
  • 3
  • 13
  • 27
  • why don't you use ng-chips? git repo: https://github.com/Gbuomprisco/ngx-chips demo: https://angular-mfppay.stackblitz.io/ It stores the items in an array, so you can easily validate the save button with the length of an array. Does it make sense? – Immad Hamid Jul 16 '18 at 04:01
  • Thanks for your suggestion. I will try ngx-chips in later. – monir tuhin Jul 16 '18 at 04:42
  • Are you mixing template driven forms and reactive forms? That seems to be reason - your "fruits" is not showing in the form - you can try this by displaying `{{ sampleForm.form .value | json }} ` in your template. – Wand Maker Jul 16 '18 at 05:12

2 Answers2

5

In your save button you can use disabled property that you already have but that should be something like this:

[disabled]="company_name === undefined || fruits.length === 0"

For other people coming for this question:

There's another great package that you can use which gives you validations for your tags and it goes by the name of ng-chips.

Git Repo: github.com/Gbuomprisco/ngx-chips

Online Demo: angular-mfppay.stackblitz.io

Immad Hamid
  • 789
  • 1
  • 8
  • 21
1

Solution

HTML:

<form #sampleForm="ngForm">

    <mat-form-field class="example-chip-list">
        <input matInput placeholder="Company Name" required="true" name="company_name" [(ngModel)]="company_name">
    </mat-form-field>

    <mat-form-field class="example-chip-list">
        <mat-chip-list #chipList>
            <mat-chip *ngFor="let fruit of fruits" [selectable]="selectable" [removable]="removable" (removed)="remove(fruit)">
                {{fruit}}
                <mat-icon matChipRemove *ngIf="removable">cancel</mat-icon>
            </mat-chip>
            <input placeholder="New fruit..." #fruitInput [formControl]="fruitCtrl" [matAutocomplete]="auto" [matChipInputFor]="chipList"
             [matChipInputSeparatorKeyCodes]="separatorKeysCodes" [matChipInputAddOnBlur]="addOnBlur" (matChipInputTokenEnd)="add($event)">
        </mat-chip-list>
        <mat-autocomplete #auto="matAutocomplete" (optionSelected)="selected($event)">
            <mat-option *ngFor="let fruit of filteredFruits | async" [value]="fruit">
                {{fruit}}
            </mat-option>
        </mat-autocomplete>
    </mat-form-field>


    <button fxFlex="30" mat-raised-button color="primary" [disabled]="!sampleForm.form.valid || company_name === undefined || fruits.length === 0">Save</button>
</form>
Akj
  • 7,038
  • 3
  • 28
  • 40