【问题标题】:How to push array of string in formArray?如何在formArray中推送字符串数组?
【发布时间】:2020-06-16 23:23:35
【问题描述】:

我需要创建这个:

instructions: ['value one' , 'value two' , 'value three'];

我正在使用 formArray 并首先在 stackblitz 上检查我的代码: https://stackblitz.com/edit/formarray-obj?file=app/app.component.ts

html:

<div class="form">
    <form id="form" [formGroup]="filmForm" (ngSubmit)="save()">
        <button type="button" (click)="addItem()"> add new row</button>
        <div formArrayName="instructions" *ngFor="let a of filmForm.get('instructions').controls; let i = index">
            <div [formGroupName]="i" style="margin-bottom: 10px;">
                <label for="name">Name:</label>
                <input type="text" name="name" formControlName="instructions">
                <br><br>
            </div>
        </div>
        <div class="submit">
            <button type="submit">Save</button>
        </div>
    </form>
</div>

TS:

registerForm: FormGroup;
submitted = false;
instructions: FormArray;
filmForm: FormGroup;
constructor(private formBuilder: FormBuilder) { }

ngOnInit() {
    this.filmForm = this.formBuilder.group({
        instructions: this.formBuilder.array([this.createItem()])
    })
}

createItem() {
    return this.formBuilder.group({
        instructions: ['']
    })
}

addItem() {
    this.instructions = this.filmForm.get('instructions') as FormArray;
    this.instructions.push(this.createItem());
}

save() {
    console.log(this.filmForm.value)
}

我正在发送对象数组:检查 stackblitz console.log 我发送喜欢

instructors = [{instructs : 'value one'} , {instructs : 'value one'}..]

但我需要发送:

 instructors = ["value one" , "value two"];

【问题讨论】:

  • 在 Angular v8 之前我不这么认为。 #关注
  • 我不明白? v8 呢?
  • 我的意思是直到 Angular 版本 8。
  • 这个answer 可能对你有帮助
  • 您可以使用 rxjs 来格式化您的数据:console.log({ instructions: this.filmForm.value.instructions.map(e=&gt; e.instructions) });。看看我的 stackblitz:stackblitz.com/edit/formarray-obj-kkszod

标签: javascript html angular


【解决方案1】:

您可以通过两种方式进行此操作。

1 - 在 save() 中使用 .map

对于想要的输出,可以使用.map in save()函数:

save() {
  const instructions = this.filmForm.value.instructions.map(inst => inst. instruction);

  console.log(instructions);
}

所需的输出将是:

["value one" , "value two"]

2 - 使用像 ng-select 这样的标签输入控件

您的用例看起来像是用于说明的标签控制用例。 有一个流行的库@ng-select/ng-select,它有一个tags 控件。

您可以在 this stackblitz 上查看此库在您的用例中的使用情况。

方法 1 是最简单的方法,但我建议您在方法 2 中使用标签控制以获得良好的用户体验。

【讨论】:

  • 好的,我得到了这个值......但是如何附加到我的表单......这个值......
  • 您能解释一下您要对这些值做什么吗?另外,您采用哪种方法?
【解决方案2】:

你可以试试这个..我有同样的问题。

制作表格

form = new FormGroup({
instructorsArray: new FormArray([]),
})

  get instructors(): FormGroup {
    return FormControl('')
  }

 addInstructors() {
    this.instructors.push(this.instructors);
  }

【讨论】:

  • this.pegadio 是什么??
  • 对不起,this.instructors.push(this.instructors);
  • 为了更好地理解做了修改。
猜你喜欢
  • 2019-10-22
  • 2020-10-07
  • 2019-04-07
  • 1970-01-01
  • 1970-01-01
  • 2018-11-16
  • 1970-01-01
  • 2021-02-19
  • 2012-03-06
相关资源
最近更新 更多