【问题标题】:Angular 8 add material chiplist with formGroupAngular 8 使用 formGroup 添加材料芯片列表
【发布时间】:2019-09-23 04:16:50
【问题描述】:

我正在尝试使用 Ng 形式添加 Angular 材料的芯片列表列表。我无法单击按钮添加新的芯片列表,也不知道如何显示新芯片列表中添加的数组值。这是一个例子 https://stackblitz.com/edit/angular-4d5vfj-g1ggqr

   <button (click)="addNewChip()">Add new Chip</button><br><br>

  <form [formGroup]="myForm">
  <mat-form-field class="example-chip-list">
  <mat-chip-list #chipList formArrayName="names">
  <mat-chip 
    *ngFor="let name of myForm.get('names').controls; let i=index;"
    [selectable]="selectable"
    [removable]="removable"
    (removed)="remove(myForm, i)">
    {{name.value}}
    <mat-icon matChipRemove *ngIf="removable">cancel</mat-icon>
  </mat-chip>
  <input placeholder="Names"
    [matChipInputFor]="chipList"
    [matChipInputSeparatorKeyCodes]="separatorKeysCodes"
    [matChipInputAddOnBlur]="addOnBlur"
    (matChipInputTokenEnd)="add($event, myForm)">
</mat-chip-list>
<mat-error>Atleast 1 name need to be added</mat-error>
</mat-form-field>
 </form>

component.ts 文件

export class ChipListValidationExample implements OnInit {
@ViewChild('chipList') chipList: MatChipList;
public myForm: FormGroup;

  // name chips
    visible = true;
  selectable = true;
  removable = true;
  addOnBlur = true;
   readonly separatorKeysCodes: number[] = [ENTER, COMMA];

// data
 data = {
  names: ['name1', 'name2']
  }

constructor(private fb: FormBuilder) {
this.myForm = this.fb.group({
  names: this.fb.array(this.data.names, this.validateArrayNotEmpty)
});
  }

ngOnInit() {
this.myForm.get('names').statusChanges.subscribe(
  status => this.chipList.errorState = status === 'INVALID'
);
}

 initName(name: string): FormControl {
return this.fb.control(name);
}

 validateArrayNotEmpty(c: FormControl) {
if (c.value && c.value.length === 0) {
  return {
    validateArrayNotEmpty: { valid: false }
  };
}
return null;
 }

  add(event: MatChipInputEvent, form: FormGroup): void {
const input = event.input;
const value = event.value;

// Add name
         if ((value || '').trim()) {
  const control = <FormArray>form.get('names');
  control.push(this.initName(value.trim()));
  console.log(control);
}

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

   remove(form, index) {
console.log(form);
form.get('names').removeAt(index);
 }

  addNewChip(){
  console.log("Yse")
   this.myForm = this.fb.group({
  names: this.fb.array(this.data.names, this.validateArrayNotEmpty)
   });
   }

}

【问题讨论】:

  • 您正在尝试将芯片添加到芯片列表或将芯片列表添加到现有表单??
  • 您需要使用 controlValueAccessor 来定义一个接口,该接口充当 Angular 表单 API 和 DOM 中的本机元素之间的桥梁。 angular.io/api/forms/ControlValueAccessor
  • 尝试以现有形式添加芯片列表。单击添加按钮时,每次都应该显示一个输入表单,我可以在其中添加筹码..
  • @Subham 请检查发布的答案

标签: angular typescript angular-material


【解决方案1】:

我希望这就是你要找的东西

  • 修改了 addChip、removeChip 方法,通过将 formControl 传递给方法来处理 FormArray 中的当前 Chiplist。
  • 修改数据以接受名称和初始值集
  • 修改了 addNewChipList 方法,将一个 formControl 添加到现有的 forArray 中
 <button (click)="addNewChipList()">Add new Chip</button><br><br>

<form [formGroup]="myForm">
<ng-container formArrayName="names"
  *ngFor="let item of myForm.get('names').controls; let i = index;">
  <mat-form-field class="example-chip-list" [formGroupName]="i">
    <mat-chip-list #chipList >
      <mat-chip *ngFor="let val of item.value.val"
        [selectable]="selectable"
        [removable]="removable"
        (removed)="removeChip(item, val)">
        {{val}}
        <mat-icon matChipRemove *ngIf="removable">cancel</mat-icon>
      </mat-chip>
      <input [placeholder]="item.value.name"
        [matChipInputFor]="chipList"
        [matChipInputSeparatorKeyCodes]="separatorKeysCodes"
        [matChipInputAddOnBlur]="addOnBlur"
        (matChipInputTokenEnd)="addChip($event, item)">
    </mat-chip-list>
    <mat-error>Atleast 1 name need to be added</mat-error>
  </mat-form-field>
</ng-container>
</form>
// data
data = {
  names: [this.initName('name1'), this.initName('name2', ['A', 'B'])]
}

constructor(private fb: FormBuilder) {
  this.myForm = this.fb.group({
    names: this.fb.array(this.data.names, this.validateArrayNotEmpty)
  });
}

ngOnInit() {
  this.myForm.get('names').statusChanges.subscribe(
    status => this.chipList.errorState = status === 'INVALID'
  );
}

initName(name: string, val: string[]=[]): FormControl {
  return this.fb.control({ name, val });
}

validateArrayNotEmpty(c: FormControl) {
  if (c.value && c.value.length === 0) {
    return {
      validateArrayNotEmpty: { valid: false }
    };
  }
  return null;
}

addChip(event: MatChipInputEvent, ctrl: FormControl): void {
  const input = event.input;
  const value = event.value;

  // Add name
  if ((value || '').trim()) {
    const control = ctrl;
    control.value.val.push(value.trim());
    console.log(control.value);
  }

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

removeChip(ctrl, val) {
  const idx = ctrl.value.val.findIndex(item => item === val);
  ctrl.value.val.splice(idx, 1);
}

addNewChipList() {
  const items = this.myForm.get('names') as FormArray;
  items.push(this.initName(`name${items.length + 1}`));
}

更新 Stackblitz https://stackblitz.com/edit/angular-4d5vfj-fzjlnm

【讨论】:

    猜你喜欢
    • 2019-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-30
    • 2021-10-23
    • 1970-01-01
    • 2019-08-01
    相关资源
    最近更新 更多