繁体   English   中英

如何在formArray中推送字符串数组?

[英]How to push array of string in 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)
}

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

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

但我需要发送:

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

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

制作表格

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

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

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

有两种方法可以让您提前完成 go。

1 - 在保存()中使用.map

对于所需的 output,您可以在save() function 中使用.map

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

  console.log(instructions);
}

所需的 Output 将是:

["value one" , "value two"]

2 - 使用标签输入控件,如 ng-select

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM