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

相关内容

热门资讯

今天上午"wepok... 今天上午"wepoker辅助器软件下载"wepoker透视最简单三个步骤(一直有辅助辅助器)-哔哩哔...
截至目前"aapok... 截至目前"aapoker透视插件"wepoker破解游戏盒子(本来真的是有辅助神器)-哔哩哔哩1)w...
透视美元局"aapo... 透视美元局"aapoker透视怎么用"wpk俱乐部是做什么的(一贯有辅助修改器)-哔哩哔哩1、进入到...
此事引发广泛关注"h... 此事引发广泛关注"hhpoker辅助"德普之星透视辅助插件(总是是真的辅助安装)-哔哩哔哩1、德普之...
透视软件"wejok... 透视软件"wejoker黑侠辅助器"aapoker透视脚本下载(总是真的是有辅助软件)-哔哩哔哩1、...
有消息称"wepok... 有消息称"wepoker高级辅助"wpk有辅助器吗(真是真的有辅助下载)-哔哩哔哩1、wepoker...
透视透视"wpk私人... 透视透视"wpk私人局有透视吗"aapoker透视脚本入口(一直真的有辅助软件)-哔哩哔哩aapok...
透视挂"智星德州插件... 透视挂"智星德州插件"wepoker黑侠辅助器正版下载(确实是有辅助插件)-哔哩哔哩1、让任何用户在...
来临"hhpkoer... 来临"hhpkoer辅助器"hhpoker透视脚本(原来是有辅助插件)-哔哩哔哩;1、完成hhpok...
透视玄学"aapok... 透视玄学"aapoker能控制牌吗"wpk德州局怎么透视(其实真的是有辅助安装)-哔哩哔哩1、下载好...