如何在角度材料 2 中使用 mat-chip 和自动完成保存所选对象 [英] How to save selected object using mat-chip and autocomplete in angular material 2

查看:17
本文介绍了如何在角度材料 2 中使用 mat-chip 和自动完成保存所选对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 Angular 6 与 Angular Material 一起使用.我正在尝试从 mat-chip 和自动完成中保存选定的对象或选定对象的列表.我能够将字符串值发送到fruits[] 数组,但无法将选定的对象发送到fruits[] 数组.请帮我找到解决办法.谢谢.

我的演示项目链接:演示代码在stackblitz上

解决方案

你可以试试这个解决方案.

我在 Stackblitz .

<块引用>

component.html

<mat-chip-list #chipList><mat-chip *ngFor="letfruit offruits;let indx=index;"[selectable]="selectable" [removable]="removable" (removed)="remove(fruit,indx)">{{水果名称}}<mat-icon matChipRemove *ngIf="removable">cancel</mat-icon></mat-chip><input placeholder="新水果..." #fruitInput [formControl]="fruitCtrl" [matAutocomplete]="auto" [matChipInputFor]="chipList"[matChipInputSeparatorKeyCodes]="separatorKeysCodes" [matChipInputAddOnBlur]="addOnBlur" (matChipInputTokenEnd)="add($event)"></mat-chip-list><mat-autocomplete #auto="matAutocomplete" (optionSelected)="selected($event)"><mat-option *ngFor="让过滤水果的果实 | async" [value]="fruit">{{水果名称}}</mat-option></mat-autocomplete></mat-form-field><pre>{{fruits|json}}</pre>

<块引用>

component.ts

import { COMMA, ENTER } from '@angular/cdk/keycodes';从@angular/core"导入 { Component, ElementRef, ViewChild };从'@angular/forms'导入{FormControl};导入 { MatAutocompleteSelectedEvent, MatChipInputEvent } from '@angular/material';从 'rxjs' 导入 { Observable };import { map, startWith } from 'rxjs/operators';/*** @title 基本芯片*/@成分({选择器:'芯片概述-示例',templateUrl: 'chips-overview-example.html',styleUrls: ['chips-overview-example.css'],})导出类 ChipsOverviewExample {可见 = 真;可选择 = 真;可移动 = 真;addOnBlur = false;separatorKeysCodes: number[] = [ENTER, COMMA];FruitCtrl = new FormControl();过滤的水果:可观察的;水果:任何= [];所有水果:任何 = [{编号:1,名称:'苹果'},{编号:2,名称:'橙色'},{编号:3,名称:'香蕉'},{编号:4,名称:'马耳他'}];@ViewChild('fruitInput') FruitInput: ElementRef;构造函数(){this.filteredFruits = this.fruitCtrl.valueChanges.pipe(开始(空),map((fruit: string | null) =>fruit ? this._filter(fruit) : this.allFruits.slice()));}添加(事件:MatChipInputEvent):无效{const input = event.input;常量值 = event.value;//添加我们的水果if ((value || '').trim()) {this.fruits.push({id:Math.random(),名称:value.trim()});}//重置输入值如果(输入){输入值 = '';}this.fruitCtrl.setValue(null);}删除(水果,索引):无效{this.fruits.splice(indx, 1);}选定(事件:MatAutocompleteSelectedEvent):无效{this.fruits.push(event.option.value);this.fruitInput.nativeElement.value = '';this.fruitCtrl.setValue(null);}私人_过滤器(值:任何):字符串[] {return this.allFruits.filter(fruit =>fruit.id === value.id);}}

I am using Angular 6 with Angular Material. I am trying to save a selected object or list of selected object from mat-chip and autocomplete. I am able to send string value to fruits[] array but can not able to send selected object in to fruits[] array. Please help me to find a solution. Thanks.

My Demo Project Link: demo code on stackblitz

解决方案

You can try this solution.

I have created a demo on Stackblitz .

component.html

<mat-form-field class="example-chip-list">
    <mat-chip-list #chipList>
        <mat-chip *ngFor="let fruit of fruits;let indx=index;" [selectable]="selectable" [removable]="removable" (removed)="remove(fruit,indx)">
            {{fruit.name}}
            <mat-icon matChipRemove *ngIf="removable">cancel</mat-icon>
        </mat-chip>
        <input placeholder="New fruit..." #fruitInput [formControl]="fruitCtrl" [matAutocomplete]="auto" [matChipInputFor]="chipList"
         [matChipInputSeparatorKeyCodes]="separatorKeysCodes" [matChipInputAddOnBlur]="addOnBlur" (matChipInputTokenEnd)="add($event)">
    </mat-chip-list>
    <mat-autocomplete #auto="matAutocomplete" (optionSelected)="selected($event)">
        <mat-option *ngFor="let fruit of filteredFruits | async" [value]="fruit">
            {{fruit.name}}
        </mat-option>
    </mat-autocomplete>
</mat-form-field>


<pre>{{fruits|json}}</pre>

component.ts

import { COMMA, ENTER } from '@angular/cdk/keycodes';
import { Component, ElementRef, ViewChild } from '@angular/core';
import { FormControl } from '@angular/forms';
import { MatAutocompleteSelectedEvent, MatChipInputEvent } from '@angular/material';
import { Observable } from 'rxjs';
import { map, startWith } from 'rxjs/operators';

/**
 * @title Basic chips
 */
@Component({
  selector: 'chips-overview-example',
  templateUrl: 'chips-overview-example.html',
  styleUrls: ['chips-overview-example.css'],
})
export class ChipsOverviewExample {
  visible = true;
  selectable = true;
  removable = true;
  addOnBlur = false;
  separatorKeysCodes: number[] = [ENTER, COMMA];
  fruitCtrl = new FormControl();
  filteredFruits: Observable<string[]>;
  fruits: any = [];
  allFruits: any = [
    {
      id: 1,
      name: 'Apple'
    },
    {
      id: 2,
      name: 'Orange'
    },
    {
      id: 3,
      name: 'Banana'
    },
    {
      id: 4,
      name: 'Malta'
    }
  ];

  @ViewChild('fruitInput') fruitInput: ElementRef;

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

  add(event: MatChipInputEvent): void {
    const input = event.input;
    const value = event.value;
    // Add our fruit
    if ((value || '').trim()) {
      this.fruits.push({
          id:Math.random(),
          name:value.trim()
      });
    }

    // Reset the input value
    if (input) {
      input.value = '';
    }

    this.fruitCtrl.setValue(null);
  }

  remove(fruit, indx): void {
    this.fruits.splice(indx, 1);
  }

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

  private _filter(value: any): string[] {
    return this.allFruits.filter(fruit => fruit.id === value.id);
  }
}

这篇关于如何在角度材料 2 中使用 mat-chip 和自动完成保存所选对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆