我正在Angular中创建一个ID查找表单。我想在一个HTML文件中根据我拥有的一组值(保持DRY)创建多个formGroups。每个formGroup都将归属于相同的函数,但使用不同的值作为参数。我需要formGroup的formControlName,占位符,标签和按钮值具有不同的值(与数组中的值关联)。
我尝试ngFor的成功有限。
var idNames = ['Organization', 'Site', 'Location', 'Device'];
示例HTML文件
<form [formGroup]='organizationForm'>
<label>
Organization Id:
<input type="text"
formControlName='organizationId'
placeholder="Organization Id">
<button type="submit" (click)="idInfo()">Search for Organization</button>
</label>
</form>
<form [formGroup]='siteForm'>
<label>
Site Id:
<input type="text"
formControlName='siteId'
placeholder="Site Id">
<button type="submit" (click)='idInfo()'>Search for Site</button>
</label>
</form>
<form [formGroup]='locationForm'>
<label>
Location Id:
<input type="text"
formControlName='locationId'
placeholder="Location Id">
<button type="submit" (click)='idInfo()'>Search for Location</button>
</label>
</form>
<form [formGroup]='deviceForm'>
<label>
Device Id:
<input type="text"
formControlName='deviceId'
placeholder="Device Id">
<button type="submit" (click)='idInfo()'>Search for Device</button>
</label>
</form>
答案 0 :(得分:0)
您可能需要一个具有多个FormControl的单个FormGroup。如果表单中的单个项目需要复杂的结构,请使用嵌套的FormGroups
在component.ts
中lookupForm: FormGroup;
idNames = ['Organization', 'Site', 'Location', 'Device'];
constructor( private fb: FormBuilder ) { this.createForm();}
createForm() {
this.lookupForm = this.fb.group({
Organization: '',
Site: '',
Location: '',
Device: ''
});
}
在component.html
中<form [formGroup]='lookupForm'>
<ng-container *ngFor="let id of idNames">
<label [attr.for]="id">{{id}}</label>
<input type="text"[formControlName]='id' [placeholder]="id" [attr.id]=id>
<button type="submit" (click)="idInfo(id)">Search for Organization</button>
</ng-container
</form>
答案 1 :(得分:0)
您可以创建新的组件或模板以使代码“ DRY”
对于模板解决方案,您可以查看以下代码:
<form [formGroup]="deviceForm">
<ng-container
[ngTemplateOutlet]="controlTemplate"
[ngTemplateOutletContext]="{labelText: 'Device Id', buttonText: 'Search for Device', controlName: 'deviceId'}"
></ng-container>
</form>
<ng-template #controlTemplate let-labelText="labelText" let-buttonText="buttonText" let let-controlName="controlName">
<label>
{{labelText}}:
<input type="text"
[formControlName]="controlName"
[placeholder]="labelText">
<button type="submit" (click)="idInfo()">{{buttonText}}</button>
</label>
</ng-template>