用条件初始化表单

时间:2018-03-11 15:09:48

标签: angular angular-forms

我想根据服务返回的结果使用表单,在我的例子中,如果约定列表不为null,则调用方法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)
        ])
    });
}

1 个答案:

答案 0 :(得分:0)

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

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

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

执行顺序为Constructor-> ngOnInit

  1. 构造函数中的if-else块是多余的 if(this.conventions)永远不会评估为真。
  2. 你在getAll()中调用你的ngOnInit方法订阅它提取响应,那就是你用它做什么?如果您认为再次调用constructor则错误。
  3. 使用构造函数调用默认情况。

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

    一旦获得结果,将你的逻辑移到subscribe中,将执行适当的方法

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