首页 > 解决方案 > 如何在formArray中推送字符串数组?

问题描述

我需要创建这个:

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"];

标签: javascripthtmlangular

解决方案


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

制作表格

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

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

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

推荐阅读