不填充模型并将其设置为angular8的形式

时间:2019-10-23 11:19:29

标签: javascript angular typescript

我有这个模型:

export interface SiteSetting {
    postSetting: PostSetting;
}

export interface PostSetting {
    showDataRecordAfterSomeDay: number;
}

并且我需要在组件中填充模型以形成表单值。

   postSettingAddFormGroup: FormGroup;
  postSettingModel: SiteSetting;

  constructor(private formBuilder: FormBuilder, private postsettingService: PostService, private alertService: AlertService, private route: Router) {
    this.postSettingModel = {} as SiteSetting;
    this.cachedSetting();
  }

  ngOnInit(): void {
    this.intialForm();
  }


  ngAfterViewInit(): void {
  }


  intialForm(): void {
    this.postSettingAddFormGroup = this.formBuilder.group({
      showDataRecordAfterSomeDay: ['', Validators.compose([Validators.required, Validators.minLength(0), Validators.maxLength(365)])]
    });
  }

  cachedSetting(): void {
    this.postsettingService.getPostSetting().subscribe(data => {
      this.postSettingModel.postSettingsModel = data
    })
  }

i使用此代码,但未使用postSettingModel

出什么问题了?我该如何解决这个模型?

1 个答案:

答案 0 :(得分:0)

我看到的是,您永远不会将表单与获取的数据连接起来。尝试这样的事情:

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.scss']
})
export class TestComponent implements OnInit {

  postSettingAddFormGroup: FormGroup;

  constructor(private formBuilder: FormBuilder, private postSettingService: BtwService) {
    this.postSettingAddFormGroup = this.formBuilder.group({
      showDataRecordAfterSomeDay: new FormControl(null, Validators.compose([Validators.required, Validators.minLength(0), Validators.maxLength(365)]))
    });
  }

  ngOnInit() {
    this.postSettingService.getPostSetting().subscribe(data => {
      this.postSettingAddFormGroup.patchValue({
        showDataRecordAfterSomeDay: data.showDataRecordAfterSomeDay
      });
    });
  }
}

首先,在构造函数中移动您创建的表单。

“ showDataRecordAfterSomeDay”是一个数字,因此您必须将其初始化为null或0而不是“”。

现在,要使用数据更新表单,可以使用“ PatchValue”。这就是ngOnInit中发生的事情。

在您的HTML中:

<form [formGroup]="postSettingAddFormGroup">
  <input type="text" formControlName="showDataRecordAfterSomeDay">
</form>

在PostSettingService中,假设您要返回PostSetting?所以:

getPostSetting(): Observable<PostSetting> {
    return of({showDataRecordAfterSomeDay: 10});
}