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