我创建了一个 Angular 响应式(Reactive)表单,其中标签将通过权限切换。我想通过创建一个组件来处理这些语义切换,该组件负责将数据作为 @Input() 并呈现特定的输入标签。处理这个问题的正确方法是什么?
有一个父 master-form.component,其中包含 'formGroup' 和一个名为 input-switch.component 的子组件。我通过 @Input() 将特定参数传递给子组件。子组件由字段值和 formControlName 组成,并通过 ngIf 切换。
这是 master-form.component html -
<form class="master-form" [formGroup]="masterForm" (ngSubmit)="submitData(masterForm)">
<label>My first field: </label>
<input-switch [setting]="'change'" [labelVal]="'first field value'" [formCtrl]="'firstField'">
</input-switch>
<label>My second field: </label>
<input-switch [setting]="'change'" [labelVal]="'second field value'"
[formCtrl]="'secondField'">
</input-switch>
<button type="submit" [disabled]="!masterForm.valid"></button>
</form>
主窗体组件类-
class MasterFormComponent implements OnInit {
masterForm: FormGroup;
constructor(private fb: FormBuilder){}
ngOnInit() {
this.masterForm = this.fb.group({
firstField: ['', Validators.maxLength(10)],
secondField: ['', Validators.maxLength(20)]
});
}
submitData(form) {
console.log('DONE!');
}
}
输入开关子组件类 -
class InputSwitch {
@Input() setting ;
@Input() labelVal;
@Input() formCtrl;
}
输入切换子组件html -
<span *ngIf="setting !== 'change'">{{labelVal}}</span>
<input *ngIf="setting === 'change'" [formControlName]="formCtrl" />
抛出错误,提及 input-switch.component 中缺少“formGroup”,并且我无法设置表单。 这里似乎有什么问题? 有没有其他方法可以实现这个功能?
最佳答案
您可以浏览此博客。它提到了如何使用 ControlValueAccessor 接口(interface)处理表单中的子组件。
Nested Reactive Forms Using ControlValueAccessors
这很复杂,但你可以尝试一下。
您还可以创建两个单独的组件,每个组件都有不同的表单元素,并使用 *ngIf 切换它们。在组件/指令中破坏它需要在每个表单字段中插入。需要正确处理模型绑定(bind),请记住 ngModel 存在于父 Controller 中。如果处理不当,可能会增加代码复杂性。
根据您的要求选择一种继续方式。
关于javascript - 如何实现我想通过子组件动态渲染表单控件的 Angular 形式的功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57661568/