【发布时间】:2019-01-08 16:39:31
【问题描述】:
我有一个使用 FormArray 添加更多标签字段的表单。我在每个字段上都使用了一个验证器,我想在每个输入了无效标签的字段下显示错误消息。问题是,我不知道如何将标签的索引传递给 *ngIf 表达式。 我尝试使用:
*ngIf="commentForm.controls.i.errors.validError"
*ngIf="commentForm.controls[i].errors.validError"
*ngIf="commentForm.controls.$i.errors.validError"
但每一个都给我错误:
TypeError:“_co.commentForm.controls.i 未定义”
TypeError:“_co.commentForm.controls[_v.context.index] 未定义”
TypeError:“_co.commentForm.controls.$i 未定义”
我怎样才能让它工作?我正在使用最新的 Angular。
代码:comment-form.component.html
<div formArrayName="tags">
<h3>Tags</h3> <button (click)="addTag()">Add Tag</button>
<div *ngFor="let tagname of tags.controls; let i=index">
<label>
Tag:
<input type="text" [formControlName]="i">
<div *ngIf="submitted && commentForm.controls.i.errors" class="errorbox">
<div *ngIf="commentForm.controls.i.errors.validError" class ="error">This tag is invalid!</div>
</div>
</label>
</div>
</div>
comment-form.component.ts:
@Component({
selector: 'app-comment-form',
templateUrl: './comment-form.component.html',
styleUrls: ['./comment-form.component.scss']
})
export class CommentFormComponent implements OnInit {
commentForm: FormGroup;
submitted = false;
success = false;
get tags() {
return this.commentForm.get('tags') as FormArray;
}
addTag() {
this.tags.push(this.formBuilder.control(''));
}
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
this.commentForm = this.formBuilder.group({
name: ['', [Validators.required, Validators.minLength(3), nameValidator()]],
email: ['', [Validators.required, emailValidator()]],
comment: ['', [Validators.required, commentValidator()]],
tags: this.formBuilder.array([''], tagsValidator())
});
}
onSubmit() {
this.submitted = true;
if (this.commentForm.invalid) {
return;
}
this.success = true;
}
}
附加信息: 添加标签有效,标签验证有效,我只需要在验证返回 false 时显示错误消息。我不能这样做,因为 *ngIf="commentForm.controls[TAGNAME].errors.validError" 不起作用而且它不起作用,因为我将标记名传递给它的方式有问题
【问题讨论】:
-
你试过了吗:
commentForm.get(i).errors.validError? -
这个给了我以下错误:ERROR TypeError: "_co.commentForm.controls.get is not a function"
-
你试过用
.controlsConfig代替.controls吗? -
有人知道这个吗?我看到'placeholder="{{param?.parameterAllowedValues[0]?.description}}"'的“无法读取未定义的属性描述”。我不能添加“?”到 [0] 的开头或结尾,让它跳过空/未定义检查,因为如果我这样做会发生另一个错误。
标签: angular