【发布时间】:2020-01-27 15:29:08
【问题描述】:
我将包含 FormControls 的 FormGroups 动态添加到 FormArray 中,并将 UI 中的表单控件显示为输入字段。我想计算在 UI 中添加的每个 FormGroup 的 sectionContent 字段中输入的字符。这完全可以只使用一个 FormGroup,因为我可以订阅 valueChanges 方法,将值的长度传递给一个变量,然后在 UI 中插入该变量。但是是否有可能使用多个动态添加的 FormGroup 及其 FormControls?问题是每个 FormGroup 都需要一个新变量注入到 html 代码中,我不确定这是否可行。也许还有另一种计算 UI 中多个字段的字符数的方法?
HTML:
<div class="container">
<div formArrayName="section" *ngFor="let section of myForm.get('section').controls; let i = index">
<div [formGroupName]="i">
<div class="row">
<div class="col-sm-8">
<div class="form-group">
<textarea class="form-control" [id]="'sectionContent' + i" placeholder="Main Content" formControlName="sectionContent"></textarea>
</div>
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-4">
<button type="button" class="btn btn-primary"
(click)="addSectionButtonClick()">Add Section</button>
</div>
</div>
</div>
组件:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators, FormArray } from '@angular/forms';
@Component({
selector: 'app-create-section',
templateUrl: './create-section.component.html',
styleUrls: ['./create-section.component.css']
})
export class CreateSectionComponent implements OnInit {
myForm: FormGroup;
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.myForm = this.fb.group({
title: ['', Validators.required],
section: this.fb.array([
this.addSectionFormGroup()
])
});
}
addSectionButtonClick(): void {
(this.myForm.get('section') as FormArray).push(this.addSectionFormGroup());
}
addSectionFormGroup(): FormGroup {
return this.fb.group({
sectionContent: ['', Validators.required]
})
}
【问题讨论】:
-
您想要每个文本区域的合并计数或计数吗?
-
获取计数然后做什么?我只想在 UI 上显示然后使用
pipes,如果您需要一些计算的计数然后获取FormArray并从中获取所有FormGroup元素并获取每个元素的计数... -
循环内
{{section.get('sectionContent').value?.length}} -
实际上,我对字符数和合并字数都感兴趣。还会有动态添加的文本区域,我想实时合并和计算单词。 @miselking,为了在 UI 中显示,你能举个管道的例子吗?
-
@Eliseo,非常感谢它成功了。我不知道我们可以直接在 UI 中查询表单。