gpt4 book ai didi

angular - 使用 *ngTemplateOutlet 的条件渲染在 formGroup 内部无法正常工作

转载 作者:行者123 更新时间:2023-12-05 07:15:05 25 4
gpt4 key购买 nike

我构建了一个可重用的表单输入,它应该在表单内呈现,或者使用父 formGroupName 或作为普通输入控件。

我的代码是这样的:

child.component.html:

 <ng-container *ngIf="hasFormGroup; then formFieldWithGroupName else formField">
</ng-container>

<ng-template #formFieldWithGroupName>
<span>control With Group Name</span>
<div formGroupName="_general">
<ng-container *ngTemplateOutlet="formField"></ng-container>

<!-- MY ISSUE HERE: directly add the template below works but not best practice -->
<!-- <input matInput placeholder="Project name"
[formControlName]="controlName"> -->
</div>
</ng-template>

<ng-template #formField>
<span>control Without Group Name</span><br>
<input matInput placeholder="Project name"
[formControlName]="controlName">
</ng-template>

child.component.ts:

import { Component, OnInit, Input } from '@angular/core';
import { FormControl, FormGroup, ControlContainer, FormGroupDirective, Validators, FormBuilder, NgModel } from '@angular/forms';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css'],
viewProviders: [{ provide: ControlContainer, useExisting: FormGroupDirective }]
})
export class ChildComponent implements OnInit {

childForm;
@Input() hasFormGroup: boolean = false;
@Input() controlName: string;
constructor(private parentF: FormGroupDirective) { }

ngOnInit() {
this.childForm = this.parentF.form;

if(this.hasFormGroup) {
this.childForm.controls._general.addControl(this.controlName, new FormControl());
} else {
this.childForm.addControl(this.controlName, new FormControl())
}
}

}

以及父组件app.component.html的内容

<form [formGroup]="parentForm">
<app-child [controlName]="'projectName'" [hasFormGroup]="false"></app-child>
<app-child [controlName]="'projectName'" [hasFormGroup]="true"></app-child>
<br>
<hr>
<app-child-2></app-child-2>

Form Value: {{parentForm.value | json}}
</form>

组内的控件未按预期工作。但是,如果我直接使用模板(不使用 ngTemplateOutlet 进行渲染),它会正确地获取这两个值。

有人可以帮我找出它不起作用的原因吗?

调试呈现的元素显示所有指令都已呈现。

这里是 Stackblitz 演示:

https://stackblitz.com/edit/angular-form-magic-4k6m9h

最佳答案

input 控件无法获取其父控件,因为它是在没有上下文的情况下注入(inject)的。将引用放在模板的内部,以便指令在查找时可以看到它:

<ng-template #formField>
<div formGroupName="_general">
<span>control Without Group Name</span><br>
<input matInput placeholder="Project name"
[formControlName]="controlName">
</div>
</ng-template>

对了,编辑:

仅用 input 替换所有代码,并在不相关时使用 null 取消 formGroupName(删除所有模板和内容):

<div [formGroupName]="hasFormGroup ? '_general' : null">
<input matInput placeholder="Project name"
[formControlName]="controlName">
</div>

关于angular - 使用 *ngTemplateOutlet 的条件渲染在 formGroup 内部无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59729982/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com