[英]Angular FormGroup: How to move formControlName to a ng-template outside FormGroupName?
This code is working:此代码有效:
<form id="list" [formGroup]="Form">
<ion-list lines="none" class="list">
<ion-item-sliding formArrayName="things" *ngFor="let item of formArray.controls; index as index">
<ion-item [formGroupName]="index">
<ng-container [ngTemplateOutlet]="thingText" [ngTemplateOutletContext]="{item:item, index:index}"></ng-container>
<ng-template #thingText let-item="item" let-index="index">
<ion-textarea id="thing-text" formControlName="content" auto-grow
value="{{ item.value.content }}"
(click)="activateEditing(index)"
(ionBlur)="leaveTheField(index)"
(keypress)="detectChange(index)"
(ionFocus)="changeScroll(index)" #activeThings>
</ion-textarea>
</ng-template>
</ion-item>
</ion-item-sliding>
</ion-list>
</form>
But I want to move the ng-template
outside the form.但我想将
ng-template
移到表单之外。 However, when I do, I get an Error: formControlName must be used with a parent formGroup directive.
但是,当我这样做时,我得到一个
Error: formControlName must be used with a parent formGroup directive.
. .
Then I tried to pass the formGroup to the ng-template:然后我尝试将 formGroup 传递给 ng-template:
<ng-container [ngTemplateOutlet]="thoughtText" [ngTemplateOutletContext]="{formGroup: Form, item:item, index:index}"></ng-container>
(...)
<ng-template #thoughtText let-item="item" let-index="index" let-formGroup="formGroup">
<div [formGroup] = "formGroup">
<ion-textarea id="thing-text" formControlName="content" auto-grow
value="{{ item.value.content }}"
(click)="activateEditing(index)"
(ionBlur)="leaveTheField(index)"
(keypress)="detectChange(index)"
(ionFocus)="changeScroll(index)" class="active-text form-control" #activeThing>
</ion-textarea>
</div>
</ng-template>
But it didn't work.但它没有用。 I get the ´Error: Cannot find control with name: 'content'`
我收到“错误:找不到名称为“内容”的控件”
What do I have to do to move the ng-template outside the form?我需要做什么才能将 ng-template 移到表单之外?
One way is to pass formControlName
to ng-template
and use [formControl]
.一种方法是将
formControlName
传递给ng-template
并使用[formControl]
。 See below.见下文。
<ng-container [ngTemplateOutlet]="thoughtText"
[ngTemplateOutletContext]="{formGroup: Form, item:item, index:index, formControlName: 'content'}"></ng-container>
(...)
<ng-template #thoughtText let-item="item" let-index="index" let-formGroup="formGroup" let-formControlName="formControlName">
<div [formGroup] = "formGroup">
<ion-textarea id="thing-text" [formControl]="formGroup.get(formControlName)" auto-grow
value="{{ item.value.content }}"
(click)="activateEditing(index)"
(ionBlur)="leaveTheField(index)"
(keypress)="detectChange(index)"
(ionFocus)="changeScroll(index)" class="active-text form-control" #activeThing>
</ion-textarea>
</div>
</ng-template>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.