Why formly doesn’t bind the value on custom control submit?

I want to use chips with autocomplete from material with formly.

So I took the example from chips with autocomplete and create a custom control as like autocomplete control defined in formly the exmpale is at the bottom.

But somehow I don’t getting the value when I click on the submit button.

What is missing here in order to make it work?

codesandbox

app.component:

import { Component } from "@angular/core";
import { FormGroup } from "@angular/forms";
import { FormlyFieldConfig } from "@ngx-formly/core";

@Component({
  selector: "app-root",
  template: `
    <form [formGroup]="form" (ngSubmit)="onSubmit(model)">
      <formly-form
        [form]="form"
        [fields]="fields"
        [model]="model"
      ></formly-form>
      <button type="submit" class="btn btn-default">Submit</button>
    </form>
  `
})
export class AppComponent {
  form = new FormGroup({});
  model = { email: "[email protected]" };
  fields: FormlyFieldConfig[] = [
    {
      key: "email",
      type: "chips",
      templateOptions: {
        label: "Email address",
        placeholder: "Enter email",
        required: true
      }
    }
  ];

  onSubmit(e: any) {
    console.log(this.model);
  }
}

chip.component:

import { COMMA, ENTER } from '@angular/cdk/keycodes';
import { AfterViewInit, Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { FormControl } from '@angular/forms';
import {
  MatAutocompleteSelectedEvent,
  MatAutocomplete,
  MatAutocompleteTrigger,
} from '@angular/material/autocomplete';
import { MatChipInputEvent } from '@angular/material/chips';
import { FieldType } from '@ngx-formly/material';
import { Observable } from 'rxjs';
import { map, startWith } from 'rxjs/operators';

@Component({
  selector: 'chips-autocomplete-example',
  template: `
    <mat-form-field class="example-chip-list">
      <mat-label>Favorite Fruits</mat-label>
      <mat-chip-list #chipList aria-label="Fruit selection">
        <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
          [formlyAttributes]="field"
          placeholder="New fruit..."
          #fruitInput
          [formControl]="fruitCtrl"
          [matAutocomplete]="auto"
          [matChipInputFor]="chipList"
          [matChipInputSeparatorKeyCodes]="separatorKeysCodes"
          (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>
  `,
})
export class ChipsAutocompleteExample extends FieldType implements OnInit, AfterViewInit {
  visible = true;
  selectable = true;
  removable = true;
  separatorKeysCodes: number[] = [ENTER, COMMA];
  fruitCtrl = new FormControl();
  filteredFruits: Observable<string[]>;
  fruits: string[] = ['Lemon'];
  allFruits: string[] = ['Apple', 'Lemon', 'Lime', 'Orange', 'Strawberry'];

  @ViewChild('fruitInput') fruitInput: ElementRef<HTMLInputElement>;
  @ViewChild('auto') matAutocomplete: MatAutocomplete;
  @ViewChild(MatAutocompleteTrigger) autocomplete: MatAutocompleteTrigger;

  constructor() {
    super();
    this.filteredFruits = this.fruitCtrl.valueChanges.pipe(
      startWith(null),
      map((fruit: string | null) =>
        fruit ? this._filter(fruit) : this.allFruits.slice()
      )
    );
  }

  add(event: MatChipInputEvent): void {
    const value = (event.value || '').trim();

    // Add our fruit
    if (value) {
      this.fruits.push(value);
    }

    // Clear the input value
    event.chipInput!.clear();

    this.fruitCtrl.setValue(null);
  }

  remove(fruit: string): void {
    const index = this.fruits.indexOf(fruit);

    if (index >= 0) {
      this.fruits.splice(index, 1);
    }
  }

  selected(event: MatAutocompleteSelectedEvent): void {
    this.fruits.push(event.option.viewValue);
    this.fruitInput.nativeElement.value = '';
    this.fruitCtrl.setValue(null);
  }

  private _filter(value: string): string[] {
    const filterValue = value.toLowerCase();

    return this.allFruits.filter(
      (fruit) => fruit.toLowerCase().indexOf(filterValue) === 0
    );
  }

  ngOnInit() {
    super.ngOnInit();
  }

  ngAfterViewInit() {
    super.ngAfterViewInit();
    // temporary fix for https://github.com/angular/material2/issues/6728
    (<any> this.autocomplete)._formField = this.formField;
  }
}

Source: Angular Material Quesions

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.