初始化一个有条件的表单

initialize a form with condition

我想根据服务返回的结果使用表单,在我的示例中,如果约定列表不为空,它会调用方法 initFormWithRequiredConvention,但问题是控制器中的约定列表未定义并在HTML中显示了公约列表

public conventions: Convention[];

constructor(private fb: FormBuilder, private conventionService: ConventionService) {
    if(this.conventions)
       this.initFormWithRequiredConvention();
    else
       this.initFormWithoutRequiredConvention();
}

public ngOnInit(): void {
    this.conventionService.getAll().subscribe((datas: any) => {
        this.conventions = datas.content;
    });
}

private initFormWithRequiredConvention(): void {
    const fb = this.fb;
    this.networkForm = this.fb.group({
        abstractName: fb.control(null, Validators.required),
        conventionsId: this.fb.array([
            this.fb.control(null, Validators.compose([Validators.required]))
        ])
    });
}

private initFormWithoutRequiredConvention(): void {
    const fb = this.fb;
    this.networkForm = this.fb.group({
        abstractName: fb.control(null, Validators.required),
        completeName: fb.control(null, Validators.required),
        countryId: fb.control(null, Validators.required),
        conventionsId: this.fb.array([
            this.fb.control(null)
        ])
    });
}

您需要了解 constructorngOnInit 之间的基本区别。

Constructor 是 class 的一种特殊类型的方法,它会在 class 的实例创建时自动调用。

ngOnInit 是 Angular 提供的生命周期挂钩,Angular 在创建组件后不久调用。

执行顺序是Constructor-> ngOnInit

  1. 构造函数中的if-else块是多余的 if(this.conventions) 永远不会计算为真。
  2. 您正在 ngOnInit 中调用您的 getAll() 方法,订阅它以提取响应,这就是您要用它做什么?如果您假设 constructor 会再次被调用,那您就错了。

使用构造函数调用您的默认案例。

constructor(private fb: FormBuilder, private conventionService:ConventionService){
this.initFormWithoutRequiredConvention();
}

一旦获得结果,将您的逻辑移入订阅中,将执行适当的方法

`public ngOnInit(): void {
            this.conventionService.getAll().subscribe((datas: any) => {
                this.conventions = datas.content;

              if(this.conventions)
                  this.initFormWithRequiredConvention();
              else
                   this.initFormWithoutRequiredConvention();
            });
        }`