@@ -1013,6 +1013,44 @@ describe('MatChipGrid', () => {
10131013 } ) ) ;
10141014 } ) ;
10151015
1016+ describe ( 'chip with form control' , ( ) => {
1017+ let fixture : ComponentFixture < ChipsFormControlUpdate > ;
1018+ let component : ChipsFormControlUpdate ;
1019+ let nativeInput : HTMLInputElement ;
1020+ let nativeButton : HTMLButtonElement ;
1021+
1022+ beforeEach ( ( ) => {
1023+ fixture = createComponent ( ChipsFormControlUpdate ) ;
1024+ component = fixture . componentInstance ;
1025+ nativeInput = fixture . nativeElement . querySelector ( 'input' ) ;
1026+ nativeButton = fixture . nativeElement . querySelector ( 'button[id="save"]' ) ;
1027+ } ) ;
1028+
1029+ it ( 'should update the form control value when pressed enter' , fakeAsync ( ( ) => {
1030+ nativeInput . value = 'hello' ;
1031+ nativeInput . focus ( ) ;
1032+ fixture . detectChanges ( ) ;
1033+
1034+ dispatchKeyboardEvent ( document . activeElement ! , 'keydown' , ENTER ) ;
1035+ fixture . detectChanges ( ) ;
1036+ flush ( ) ;
1037+
1038+ expect ( component . keywordChipControl . value ) . not . toBeNull ( ) ;
1039+ expect ( component . keywordChipControl . value . length ) . toBe ( 1 ) ;
1040+ expect ( nativeButton . disabled ) . toBeFalsy ( ) ;
1041+
1042+ nativeInput . value = 'how are you ?' ;
1043+ nativeInput . focus ( ) ;
1044+ fixture . detectChanges ( ) ;
1045+
1046+ dispatchKeyboardEvent ( document . activeElement ! , 'keydown' , ENTER ) ;
1047+ fixture . detectChanges ( ) ;
1048+ flush ( ) ;
1049+
1050+ expect ( component . keywordChipControl . value . length ) . toBe ( 2 ) ;
1051+ } ) ) ;
1052+ } ) ;
1053+
10161054 function createComponent < T > (
10171055 component : Type < T > ,
10181056 direction : Direction = 'ltr' ,
@@ -1218,3 +1256,37 @@ class ChipGridWithRemove {
12181256 this . chips . splice ( event . chip . value , 1 ) ;
12191257 }
12201258}
1259+
1260+ @Component ( {
1261+ template : `
1262+ <mat-form-field>
1263+ <mat-label>Keywords</mat-label>
1264+ <mat-chip-grid #chipGrid [formControl]="keywordChipControl">
1265+ @for (keyword of keywords; track keyword) {
1266+ <mat-chip-row>{{keyword}}</mat-chip-row>
1267+ }
1268+ </mat-chip-grid>
1269+ <input placeholder="New keyword..." [matChipInputFor]="chipGrid" (matChipInputTokenEnd)="add($event)">
1270+ </mat-form-field>
1271+ <button id="save" [disabled]="!keywordChipControl.valid">Save</button>
1272+ <button >Cancel</button>` ,
1273+ standalone : false ,
1274+ } )
1275+ class ChipsFormControlUpdate {
1276+ keywords = new Array < string > ( ) ;
1277+ keywordChipControl = new FormControl ( ) ;
1278+
1279+ constructor ( ) {
1280+ this . keywordChipControl . setValidators ( Validators . required ) ;
1281+ }
1282+
1283+ add ( event : MatChipInputEvent ) : void {
1284+ const value = ( event . value || '' ) . trim ( ) ;
1285+
1286+ if ( value ) {
1287+ this . keywords . push ( value ) ;
1288+ }
1289+
1290+ event . chipInput . clear ( ) ;
1291+ }
1292+ }
0 commit comments