markdown Angular:ReactiveForm - 使用数组

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown Angular:ReactiveForm - 使用数组相关的知识,希望对你有一定的参考价值。

See working example at [stackblitz](https://stackblitz.com/edit/angular-gazukr) and full [tutorial](https://blog.karmacomputing.co.uk/angular-6-dynamically-add-rows-reactive-forms-how-to/).

## Module
Import `ReactiveFormsModule` to a shared module.
``` typescript
\!h import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
\!h  imports:      [ BrowserModule, FormsModule, ReactiveFormsModule ],
  declarations: [ AppComponent, HelloComponent, ProductFormComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }
```

## Component
- Import `FormBuilder`, `FormGroup`, `FormArray`, `FormControl` to the component.
- Add `FormBuilder` in the `constructor`.
- 
``` typescript
\!h import { FormBuilder, FormGroup, FormArray, FormControl } from '@angular/forms';

@Component({
  selector: 'app-product-form',
  templateUrl: './product-form.component.html',
  styleUrls: ['./product-form.component.css']
})
export class ProductFormComponent implements OnInit {
  constructor(
\!h   private fb: FormBuilder
  ) { }

  productForm: FormGroup;
}
```

- Initialize `FormBuilder` creating the `FormGroup` structure.
``` typescrypt
  ngOnInit() {
    // Initiate the form structure
    this.productForm = this.fb.group({
      title: [],
      selling_points: this.fb.array([
          this.fb.group({
            point:''
          })
        ])
    });
  }
```

- Methods to be called from the template
``` typescrypt
  get sellingPoints() {
    return this.productForm.get('selling_points') as FormArray;
  }

  addSellingPoint() {
    this.sellingPoints.push(this.fb.group({point:''}));
  }

  deleteSellingPoint(index) {
    this.sellingPoints.removeAt(index);
  }
```

## Template

``` html
<h1>Edit Product</h1>

\!h <form [formGroup]="productForm">

  <label>
\!h   Title: <input formControlName="title" />
  </label>

  <h2>Selling Points</h2>
\!h <div formArrayName="selling_points">
    <div 
\!h      *ngFor="let item of sellingPoints.controls; let pointIndex=index"
      [formGroupName]="pointIndex">
      <label>
\!h      Selling Point: <input formControlName="point" />
      </label>
\!h     <button type="button" (click)="deleteSellingPoint(pointIndex)">
        Delete Selling Point
      </button>
    </div>
    <br />
\!h    <button type="button" (click)="addSellingPoint()">
      Add Seeling Points
    </button>
  </div>
  
</form>

<p>
  {{ this.productForm.value | json }}
</p>
```

以上是关于markdown Angular:ReactiveForm - 使用数组的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Angular 世界之外发生更改时更新 Angular 2 Reactive 表单字段

如何使用 angular2 Reactive 表单构建嵌套数组?

Angular Reactive Form 的一个具体使用例子

typescript 使用FormBuilder和AngularMaterial的Angular - Reactive Form

Angular Reactive Form 的深拷贝?

Angular Reactive Form 中的 DOB 验证