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、打开软件启动之后找到中间准...
必备透视!hhpoker怎么防... 必备透视!hhpoker怎么防作必弊,aa poker透视软件,演示教程(有挂功能)-哔哩哔哩1、h...
曝光透视!werplan辅助软... 曝光透视!werplan辅助软件!竟然真的有辅助方法(有挂透明挂)-哔哩哔哩1、下载好werplan...
详细透视!wepoker轻量版... 您好,wepoker轻量版透视系统这款游戏可以开挂的,确实是有挂的,需要了解加去威信【1367043...
揭幕透视!epoker免费透视... 揭幕透视!epoker免费透视脚本!本来真的是有辅助方法(有挂教程)-哔哩哔哩epoker免费透视脚...
教你透视!xpoker辅助助手... 教你透视!xpoker辅助助手,wpk辅助是什么,演示教程(真是有挂)-哔哩哔哩1、玩家可以在wpk...
详细透视!哈糖大菠萝有没有挂!... 详细透视!哈糖大菠萝有没有挂!确实真的是有辅助工具(确实有挂)-哔哩哔哩1、哈糖大菠萝有没有挂模拟器...
了解透视!wepoker怎么下... 了解透视!wepoker怎么下载游戏,aapoker插件下载,妙计教程(有挂教程)-哔哩哔哩;1、实...
关于透视!来玩app破解!一贯... 关于透视!来玩app破解!一贯一直总是有辅助插件(有挂秘诀)-哔哩哔哩1、来玩app破解破解器简单,...
解谜透视!pokermaste... 解谜透视!pokermaster破解版,德州hhpoker是真的吗,课程教程(竟然有挂)-哔哩哔哩1...