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; } }

相关内容

热门资讯

透视脚本!拱趴大菠萝有什么挂(... 透视脚本!拱趴大菠萝有什么挂(透视)掌中乐游戏中心脚本(竟然有辅助app)-哔哩哔哩1、掌中乐游戏中...
透视肯定!wepoker是不是... 透视肯定!wepoker是不是有人用挂(透视)蜀山四川破解好友版辅助(确实存在有辅助软件)-哔哩哔哩...
透视工具!we poker游戏... 透视工具!we poker游戏下(透视)闲逸碰胡外桂(一贯真的是有辅助安装)-哔哩哔哩1、任何闲逸碰...
经核实!wepoker辅助是真... 经核实!wepoker辅助是真的假的(透视)途游手游辅助(竟然存在有辅助软件)-哔哩哔哩1、途游手游...
推出新举措!约局吧作必弊脚本(... 推出新举措!约局吧作必弊脚本(透视)中至余干小程序辅助安装(原来是有辅助辅助器)-哔哩哔哩1、用户打...
透视真的!智星菠萝辅助(透视)... 透视真的!智星菠萝辅助(透视)新星游辅助软件免费版(一直是真的辅助下载)-哔哩哔哩新星游辅助软件免费...
做出回应!wpk辅助软件(透视... 做出回应!wpk辅助软件(透视)新荣耀辅助安装(一直有辅助插件)-哔哩哔哩1、下载好新荣耀辅助安装正...
透视有挂!pokemmo手机脚... 您好,微信小程序开发这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054】很多玩家...
透视黑科技!hhpoker脚本... 透视黑科技!hhpoker脚本下载(透视)约战大同辅助(原来是真的辅助修改器)-哔哩哔哩1、约战大同...
备受关注的!wejoker辅助... 备受关注的!wejoker辅助脚本(透视)微乐小程序卡五星脚本(确实真的有辅助下载)-哔哩哔哩;微乐...