在 formArray 中存储和显示输入消息

Store and display input message in formArray

我创建了一个输入字段,用户可以在其中输入消息,然后在键入时输入我想显示此消息。

export class AppComponent  {
 
  myForm: FormGroup;

  constructor(private fb: FormBuilder) {
    this.createForm();
  }


  onEnter() {
    this.addThing();
  }

  get things() {
    return this.myForm.get('things') as FormArray;
  }

  private createForm() {
    this.myForm = this.fb.group({
      things: this.fb.array([
        this.fb.control('')
      ])
    });
  }

  private addThing() {
    this.things.push(this.fb.control(''));
  }
}

Html:

<div class="display-text">
                            <p
                               *ngFor="let thing of things.controls; let i=index">{{thing.value}}
                            >
                                {{ message.value | json}}
                            </p>
                        </div>
<div class="input">
                <form [formGroup]="myForm">
                    <ng-container formArrayName="things">
                        <ng-container
                            ngFor="let thing of things.controls; let i = index "
                        >
                            <input
                                type="text"
                                (keyup.enter)="onEnter()"
                            />
                        </ng-container>
                    </ng-container>
                </form>
            </div>

按回车键时,window 中不显示消息。有人可以帮忙吗?

问题似乎是没有值存储在 formArray

我稍微简化了您的解决方案。

<div class="display-text">
  <p *ngFor="let thing of things.controls;">
    {{ thing.value }}
  </p>
</div>

<div class="input" [formGroup]="myForm">
  <input type="text" formControlName="inputValue" (keyup.enter)="addThing()" />
</div>

和 TS 代码

  constructor(private fb: FormBuilder) {
    this.createForm();
  }

  get things() {
    return this.myForm.get('things') as FormArray;
  }

  private createForm() {
    this.myForm = this.fb.group({
      inputValue: this.fb.control(''),
      things: this.fb.array([this.fb.control('')]),
    });
  }

  private addThing() {
    this.things.push(this.fb.control(this.myForm.get('inputValue').value));
  }

stackblitz

我看不出你在这里真的需要一个表单组,我只会使用一个表单控件作为输入和一个表单数组,或者甚至只是一个“常规”JS 数组,我可能只会使用它,但无论如何formarray 的使用示例:

TS:

myInput = this.fb.control('');
things = this.fb.array([]);

constructor(private fb: FormBuilder) {}

addThing() {
  this.things.push(this.fb.control(this.myInput.value)); // push value to formarray
  this.myInput.reset(); // reset input field
}

和模板:

<input [formControl]="myInput" (keyup.enter)="addThing()" />

<p *ngFor="let thing of things.controls">
  {{ thing.value }}
</p>

STACKBLITZ