programatically seelect angular mat chip values

Viewed 67

we have some selectable dropdowns using mat chip as a component. The requirement is that when there are some values in the Url query string, then those values should also be pre selected in the relevant multi select option. am fairly new to angular. have been able to get values from the url into relevant property arrays but cant seem to figure out how to programatically select those values for each of the multi select dropdown.

code is as under:

mat chip component:

<mat-expansion-panel class="shadow-none" style="box-shadow:none !important">
  <mat-expansion-panel-header>
    <mat-panel-title>
      {{label}} 
    </mat-panel-title>
    <mat-panel-description>

    </mat-panel-description>
  </mat-expansion-panel-header>
  <div >
  <mat-chip-list>      
    <mat-chip *ngFor="let option of selectedOptions" [selectable]="selectable" [removable]="removable"
    (removed)="remove(option)">
    {{option.name}}
    <button matChipRemove *ngIf="removable">
      <mat-icon>cancel</mat-icon>
    </button>
  </mat-chip>
  </mat-chip-list>
  <div class="w-full mt-2" style="border-width: 1px; border-radius: 6px; align-items: stretch;">
    <input class="w-full p-2" placeholder="Select options" #inputValue [formControl]="optionCtrl" [matAutocomplete]="auto">
    <mat-autocomplete #auto="matAutocomplete" (optionSelected)="selected($event)">
      <mat-option *ngFor="let option of filteredOptions | async" [value]="option.id">
        <span class="multiLine">
          <p style="font-weight:bold">{{option.name}}</p>
          <p>{{option.description}}</p>
        </span>
      </mat-option>
    </mat-autocomplete>
  </div>

  </div>

</mat-expansion-panel>

Typescript file:

@Component({
  selector: 'app-select-dropdown',
  templateUrl: './select-dropdown.component.html',
  styleUrls: ['./select-dropdown.component.scss']
})
export class SelectDropdownComponent implements AfterViewInit {

  @Input() options: any[];
  @Input() selection: any;
  @Input() label: string;
  @Output() selectionChange = new EventEmitter<any[]>();
  
  selectable = true;
  removable = true;
  separatorKeysCodes: number[] = [ENTER, COMMA];
  optionCtrl = new FormControl();

  filteredOptions: Observable<any[]>;
  selectedOptions: any[];

  @ViewChild('inputValue') inputValue: ElementRef<HTMLInputElement>;

  constructor() { 
    this.selectedOptions = [];
    this.filteredOptions = this.optionCtrl.valueChanges.pipe(
      startWith(null),
      map((option: any | null) => option ? this._filter(option) : this.options.slice())
    );
  }
  
  remove(option: any): void {
    const index = this.selectedOptions.indexOf(option);
    if (index >= 0) {
      this.selectedOptions.splice(index, 1);
    }
    this.inputValue.nativeElement.value = '';
    this.optionCtrl.setValue(null);
    this.selectionChange.emit(this.selectedOptions.map(function(a) { return a.id}))
  }

    selected(event: MatAutocompleteSelectedEvent): void {
    this.selectedOptions.push(this.options.find(x => x.id == event.option.value))
    this.inputValue.nativeElement.value = '';
        this.optionCtrl.setValue(null);       
        this.selectionChange.emit(this.selectedOptions.map(function (a) { return a.id }));
        setTimeout(() => {
            this.inputValue.nativeElement.blur();
           // this.inputValue.nativeElement.focus();
        })


  }
  
 
 ngAfterViewInit(): void {
  }

}

Filter page sample:

<div class="mt-2 no-shadow" matTooltip="abc.">
                        <app-select-dropdown [options]="filterData.investmentProgramPeriods"
                                             [(selection)]="filters.investmentPeriodId" [label]="'label'">
                        </app-select-dropdown>
                    </div>
                    <div class="mt-2 no-shadow" matTooltip="tooltip.">
                        <app-select-dropdown [options]="filterData.utilityServiceAreas"
                                             [(selection)]="filters.untilityServiceId" [label]="'Utility Service Area'">
                        </app-select-dropdown>
                    </div>
    

any help appreciated..

1 Answers

I don't see where is the [] which holds the strings from url which are supposed to go into the chip list. But what if you push those received values to selectedOptions? Your chip-list should update. e.g this.selectedOptions = [...this.selectedOptions, ...urlStrings] cd will run and template will update.

Related