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

相关内容

热门资讯

现有关情况通报如下!aapok... 您好,新众亿卡看底牌这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054】很多玩家...
解迷透视!哈糖大菠萝有没有挂,... 解迷透视!哈糖大菠萝有没有挂,约局吧德州可以透视吗(透视)真是有辅助脚本(哔哩哔哩)1、约局吧德州可...
相较于以往!wpk俱乐部是做什... 相较于以往!wpk俱乐部是做什么的,赣牌圈总输,确实真的有辅助脚本(哔哩哔哩)1)赣牌圈总输有没有挂...
了解透视!约局吧app有挂吗,... 了解透视!约局吧app有挂吗,xpoker辅助工具(透视)好像有辅助技巧(哔哩哔哩)1、约局吧app...
刚刚!wepoker公共底牌,... 刚刚!wepoker公共底牌,乐酷有没有挂,其实是真的有辅助神器(哔哩哔哩)乐酷有没有挂是不是有人用...
揭幕透视!pokemmo辅助器... 揭幕透视!pokemmo辅助器脚本下载,菠萝德州透视脚本(透视)原来真的有辅助教程(哔哩哔哩)1、任...
有了最新消息!德普之星怎么设置... 有了最新消息!德普之星怎么设置埋牌,微玩体育辅助器,切实真的是有辅助技巧(哔哩哔哩)进入游戏-大厅左...
揭幕透视!sohoo竞技联盟辅... 揭幕透视!sohoo竞技联盟辅助器,拱趴大菠萝辅助神器(透视)一贯一直总是有辅助app(哔哩哔哩)1...
据报道!hhpoker怎么防作... 据报道!hhpoker怎么防作必弊,浙江宝宝游戏辅助器,其实是真的有辅助方法(哔哩哔哩)1、该软件可...
曝光透视!智星菠萝辅助,智星德... 曝光透视!智星菠萝辅助,智星德州插件2024最新版(透视)果然有辅助软件(哔哩哔哩)曝光透视!智星菠...