|
| 1 | +import {LiveAnnouncer} from '@angular/cdk/a11y'; |
| 2 | +import {Component, inject, signal} from '@angular/core'; |
| 3 | +import {disabled, form, FormField} from '@angular/forms/signals'; |
| 4 | +import {MatButtonModule} from '@angular/material/button'; |
| 5 | +import {MatChipInputEvent, MatChipsModule} from '@angular/material/chips'; |
| 6 | +import {MatFormFieldModule} from '@angular/material/form-field'; |
| 7 | +import {MatIconModule} from '@angular/material/icon'; |
| 8 | + |
| 9 | +/** |
| 10 | + * @title Chips with form field |
| 11 | + */ |
| 12 | +@Component({ |
| 13 | + selector: 'chips-form-field-example', |
| 14 | + templateUrl: 'chips-form-field-example.html', |
| 15 | + styleUrl: 'chips-form-field-example.css', |
| 16 | + imports: [FormField, MatButtonModule, MatFormFieldModule, MatChipsModule, MatIconModule], |
| 17 | +}) |
| 18 | +export class ChipsFormFieldExample { |
| 19 | + readonly keywordsFormModel = signal({ |
| 20 | + words: ['angular', 'how-to', 'tutorial', 'accessibility'], |
| 21 | + enabled: true, |
| 22 | + }); |
| 23 | + |
| 24 | + readonly keywordsForm = form(this.keywordsFormModel, p => { |
| 25 | + disabled(p, { |
| 26 | + when: ({valueOf}) => !valueOf(p.enabled), |
| 27 | + }); |
| 28 | + }); |
| 29 | + |
| 30 | + announcer = inject(LiveAnnouncer); |
| 31 | + |
| 32 | + protected removeKeyword(keyword: string) { |
| 33 | + this.keywordsFormModel.update(keywords => { |
| 34 | + const index = keywords.words.indexOf(keyword); |
| 35 | + if (index < 0) { |
| 36 | + return keywords; |
| 37 | + } |
| 38 | + |
| 39 | + keywords.words.splice(index, 1); |
| 40 | + this.announcer.announce(`removed ${keyword}`); |
| 41 | + return {...keywords}; |
| 42 | + }); |
| 43 | + } |
| 44 | + |
| 45 | + protected add(event: MatChipInputEvent): void { |
| 46 | + const value = (event.value || '').trim(); |
| 47 | + |
| 48 | + // Add our keyword |
| 49 | + if (value) { |
| 50 | + this.keywordsFormModel.update(keywords => ({...keywords, words: [...keywords.words, value]})); |
| 51 | + } |
| 52 | + |
| 53 | + // Clear the input value |
| 54 | + event.chipInput!.clear(); |
| 55 | + } |
| 56 | +} |
0 commit comments