【问题标题】:Angular PrimeNG - get comma separated values from input and store as arrayAngular PrimeNG - 从输入中获取逗号分隔值并存储为数组
【发布时间】:2020-09-11 00:06:35
【问题描述】:

我正在尝试使用来自 prime ng 的逗号分隔芯片组件作为表单中的输入字段。我希望能够提取输入字段中输入的值并将它们作为单独的值存储在数组中。我试图在 stackblitz [link below] 中重新创建问题 nut 无法将值转换为字符串进行操作,这可能是由于使用不当和未正确绑定。任何意见表示赞赏。

https://stackblitz.com/edit/primeng-chips-demo-4a6hfi?file=src%2Fapp%2Fapp.component.ts

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    这是您的代码的问题:

    1. app.component.hmtl:使用 formControlName 时不需要使用 [(ngModel)]。这两件事做同样的事情,所以你应该只使用它们,这取决于你想要做什么。如果您的组件是在响应式表单中定义的,那么合乎逻辑的做法是使用 formControlName 并将其绑定到 .ts 文件中 FormGroup 的 FormControl。
    2. app.component.ts:正如我所说,您必须在您的 FormGroup 中创建一个 FormControl,其名称与您在 .html 文件中定义的名称相同,以将其绑定到组件。然后通过 FormGroup 访问控件的值。

    app.component.html:

    <form
    [formGroup]="aForm"
    (ngSubmit)="onSubmit()">
      <label>Comma Separator</label>
      <p-chips 
      formControlName="valuesArray"
      separator=","></p-chips>
      <button type="submit">Submit</button>
    </form>
    

    app.component.ts:

    import { Component } from '@angular/core';
    import {MenuItem} from 'primeng/api';
    import {FormBuilder, FormControl, FormGroup} from '@angular/forms'
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html'
    })
    export class AppComponent {
    
        valuesArray: [];
        
      aForm: FormGroup;
    
      constructor(
        private _formBuilder: FormBuilder
      ){
        this.aForm = new FormGroup({
          ValuesArray: new FormControl('')
        })
      }
    
    
        onSubmit() {
          let stringIn = this.aForm.controls.ValuesArray.value;
          stringIn = stringIn.split(',');
          for (let i =0; i < stringIn.length; i++){
            console.log(stringIn[i]);
          }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2011-05-30
      • 2021-12-23
      • 1970-01-01
      • 1970-01-01
      • 2011-02-26
      • 2019-10-25
      • 2013-03-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多