【发布时间】:2020-08-18 10:39:13
【问题描述】:
我有以下用于多种形式的输入字段的模板(请忽略 objToKeys - 它是自定义管道并且有效):
<div [formGroup]="form">
<ion-item>
<ion-label color="primary" position="floating">{{ label }}</ion-label>
<ion-input type="text" formControlName="{{ controlName }}"></ion-input>
</ion-item>
<div *ngIf="form.controls[controlName].touched && form.controls[controlName].errors" class="form-error-messages">
<div *ngFor="let key of form.controls[controlName].errors | objToKeys">
<ion-icon color="danger" name="alert-outline"></ion-icon>
<ion-label class="ion-padding-start" color="danger" class="ion-align-items-end">
{{ form.controls[controlName].errors[key].message }}
</ion-label>
</div>
</div>
</div>
我尝试通过创建自定义组件来简化此模板: component.ts
import { Component, OnInit, Input } from '@angular/core';
import { FormGroup } from '@angular/forms';
@Component({
selector: 'app-form-input',
templateUrl: './form-input.component.html',
styleUrls: ['./form-input.component.scss'],
})
export class FormInputComponent implements OnInit {
@Input() label: string;
@Input() controlName: string;
@Input() form: FormGroup;
constructor() {}
ngOnInit() {}
}
component.html
<div [formGroup]="form">
<ion-item>
<ion-label color="primary" position="floating">{{ label }}</ion-label>
<ion-input type="text" formControlName="{{ controlName }}"></ion-input>
</ion-item>
<div *ngIf="form.controls.name.touched && form.controls.name.errors" class="form-error-messages">
<div *ngFor="let key of form.controls.name.errors | objToKeys">
<ion-icon color="danger" name="alert-outline"></ion-icon>
<ion-label class="ion-padding-start" color="danger" class="ion-align-items-end">
{{ form.controls.name.errors[key].message }}
</ion-label>
</div>
</div>
</div>
请注意,在上面的 html 中,输入被包裹在一个带有 [formGroup]="form" 的 div 中。我不包装它然后Angular抱怨formControl没有包含在formgroup中。 但请注意,调用它的父组件具有 [formGroup] 属性。
<form [formGroup]="form" (ngSubmit)="onSubmit()" #formRef="ngForm">
<app-form-input [label]="'Insitution Name'" [controlName]="'name'" [form]="form"></app-form-input>
<app-actions
slot="end"
[itemType]="'summary'"
[actionMode]="'answer'"
[formMode]="formMode"
(saveSummary)="submitForm()"
(cancelSummary)="onCancel()"
></app-actions>
</form>
那么为什么 Angular 最初会抱怨,我的解决方案是否正确?这是实现组件复用的好方法吗?
【问题讨论】:
-
这不是正确的方法。它给角度变化检测周期带来了问题
-
仍在尝试调试
标签: html angular typescript angular-reactive-forms