Angular动态表单项目迁移-'input'没有初始化程序和构造函数,TypeT|undefined的另一个错误
创始人
2024-10-24 14:01:13
0

这个问题通常发生在将 Angular 旧版代码升级到新版的过程中。原因是在旧版中,可能会在构造函数中初始化值,但在新版中,它会优先使用使用输入属性进行初始化,然后才会执行构造函数。解决方法是将输入属性值初始化放在构造函数之前,在组件中添加 ngAfterViewInit() 生命周期钩子方法。以下是示例代码:

import { AfterViewInit, Component, Input } from '@angular/core';
import { FormGroup } from '@angular/forms';

@Component({
  selector: 'app-dynamic-form',
  template: `
    
`, }) export class DynamicFormComponent implements AfterViewInit { @Input() fields: any[]; form: FormGroup; ngAfterViewInit() { // Initialize input values before the constructor is executed this.fields = this.fields || []; // Initialize the form after the input values this.form = this.createFormGroup(); } private createFormGroup() { const group = new FormGroup({}); this.fields.forEach((field) => { const control = field.required ? new FormControl(field.value || '', Validators.required) : new FormControl(field.value || ''); group.addControl(field.name, control); }); return group; } }

相关内容

热门资讯

曝光透视!哈糖大菠萝怎么挂!本... 曝光透视!哈糖大菠萝怎么挂!本来真的有辅助插件(竟然有挂)-哔哩哔哩1、超多福利:超高返利,海量正版...
专业透视!pokerworld... 专业透视!pokerworld破解版下载!真是一直总是有辅助软件(有挂秘诀)-哔哩哔哩1、让任何用户...
解密透视!德州真人透视脚本!果... 解密透视!德州真人透视脚本!果然有辅助app(有挂细节)-哔哩哔哩1、任何德州真人透视脚本透视是真的...
辅助透视!hardrock透视... 辅助透视!hardrock透视工具!其实真的是有辅助脚本(有挂秘笈)-哔哩哔哩1、金币登录送、破产送...
解密透视!pokermaste... 解密透视!pokermaster辅助器!果然真的是有辅助工具(有挂讲解)-哔哩哔哩1、pokerma...
必备透视!拱趴大菠萝有什么挂!... 必备透视!拱趴大菠萝有什么挂!果然真的是有辅助工具(有挂透视)-哔哩哔哩1、首先打开拱趴大菠萝有什么...
推荐透视!约局吧德州透视!确实... 推荐透视!约局吧德州透视!确实一直都是有辅助攻略(的确有挂)-哔哩哔哩1、约局吧德州透视辅助软件下载...
必备透视!拱趴大菠萝有什么挂!... 必备透视!拱趴大菠萝有什么挂!一直一直总是有辅助软件(有挂方式)-哔哩哔哩1)拱趴大菠萝有什么挂辅助...
科普透视!xpoker辅助工具... 科普透视!xpoker辅助工具!一贯是真的有辅助神器(确实有挂)-哔哩哔哩一、xpoker辅助工具游...
科普透视!德州真人透视脚本!本... 科普透视!德州真人透视脚本!本来存在有辅助技巧(有挂攻略)-哔哩哔哩德州真人透视脚本能透视中分为三种...