简体   繁体   English

如何在Angular中使用动态表单(从api获取值以获取更新表单)?

[英]How to work with Dynamic Forms (get values from api for update form) in Angular?

I have a Component: 我有一个组件: 零件 , where i need to update a form. ,我需要更新表格。 On init, i am dispatching action to load the detail, and subscribed to success-action, where i will create formControls. 在初始化时,我将分派动作以加载详细信息,并订阅了成功动作,我将在其中创建formControls。 I am getting the data from store, but still i always get this error, in all the forms : 我从存储中获取数据,但是仍然总是以各种形式出现此错误

Cannot read property 'name' of undefined 无法读取未定义的属性“名称”

This is how the form looks when there is the above error, 这是出现上述错误时表格的外观, 屏幕截图 . And this is how the form should be looking, 这就是表格的外观, 屏幕截图 .

I tried for many hours but could not figure wIere i was going wrong. 我尝试了许多小时,但无法弄清楚我要去哪里错了。

component.ts component.ts

 formGroup: FormGroup; ngOnInit() { this.store.dispatch(new fromCourse.LoadCardDetails()); this.actionsSubject$ .pipe(filter(action => action.type === CourseActionTypes.LOAD_CARD_DETAILS_SUCCESS)) .subscribe((data: {type, payload: ICardContent } ) => { this.formGroup = new FormGroup({ name: new FormControl(`${data.payload.name}`, []), content_type: new FormControl(`${data.payload.content_type}`), actual_content: new FormControl(`${data.payload.actual_content}`), content_url: new FormControl(`${data.payload.content_url}`), additional_content: new FormControl(`${data.payload.additional_content}`), media_type: new FormControl(`${data.payload.media_type}`), media_source: new FormControl(`${data.payload.media_source}`), language_id: new FormControl(`${data.payload.language_id}`), thumbnail: new FormControl(`${data.payload.thumbnail}`), }); }); } get content_type () { return this.formGroup.get('content_type'); } get name () { return this.formGroup.get('name'); } get actual_content () { return this.formGroup.get('actual_content'); } get content_url () { return this.formGroup.get('content_url'); } get additional_content () { return this.formGroup.get('additional_content'); } get media_type () { return this.formGroup.get('media_type'); } get media_source () { return this.formGroup.get('media_source'); } get language_id () { return this.formGroup.get('language_id'); } get thumbnail () { return this.formGroup.get('thumbnail'); } 

component.html component.html

 <form novalidate class="mainForm" [style.fontSize.px]="15" [formGroup]="formGroup"> <div> <h3 class="sHeading"> Form Type </h3> <mat-form-field appearance="fill" class="formField"> <mat-select placeholder="Select Type" formControlName="content_type"> <mat-option #formType class="option" *ngFor="let type of types" [value]="type" (click)="updateFormType(formType.value)"> {{type}} </mat-option> </mat-select> </mat-form-field> </div> <div> <h3 class="sHeading"> Name </h3> <mat-form-field appearance="outline" class="formField"> <input matInput placeholder="Name should have 3 characters min." formControlName="name"> </mat-form-field> </div> <div> <h3 class="sHeading"> Content </h3> <mat-form-field appearance="outline" class="formField"> <textarea matInput placeholder="Describe the content" rows=6 formControlName="actual_content"></textarea> </mat-form-field> </div> <div class="button-container"> <button mat-raised-button type="submit" class="submitBtn" (click)="onSubmit(formGroup.value)">Update Form</button> </div> </form> 

Thanks in advance. 提前致谢。

Might be, Form is getting loaded before the API call is getting completed. 可能是,在API调用完成之前就已经加载了Form。 Create a Flag and set to true once we receive API response. 收到API响应后,创建一个Flag并将其设置为true。

In Template, you can handle using *ngIf. 在模板中,您可以使用* ngIf处理。

<div *ngIf="dataLoaded"></div>

Component: 零件:

dataLoaded = false;
ngOnInit() {
    this.store.dispatch(new fromCourse.LoadCardDetails());

    this.actionsSubject$
        .pipe(filter(action => action.type === CourseActionTypes.LOAD_CARD_DETAILS_SUCCESS))
        .subscribe((data: {type, payload: ICardContent } ) => {
          this.dataLoaded = true;
          this.formGroup = new FormGroup({
            name: new FormControl(`${data.payload.name}`, []),
            content_type: new FormControl(`${data.payload.content_type}`),
            actual_content: new FormControl(`${data.payload.actual_content}`),
            content_url: new FormControl(`${data.payload.content_url}`),
            additional_content: new FormControl(`${data.payload.additional_content}`),
            media_type: new FormControl(`${data.payload.media_type}`),
            media_source: new FormControl(`${data.payload.media_source}`),
            language_id: new FormControl(`${data.payload.language_id}`),
            thumbnail: new FormControl(`${data.payload.thumbnail}`),
          });
        });
  }

I'm sure it's because you're adding get ters to your code before even setting the this.formGroup . 我敢肯定这是因为您要在代码中添加get this.formGroup ,甚至还要设置this.formGroup These get ters will not wait for your formGroup to be initialized and will call methods on them which would end up giving you errors on the console. 这些get TER值不会等待你的formGroup被初始化,并调用它们的方法,其最终将让您在控制台上的错误。

You should set the form in ngOnInit and then call the patchValue method on it to set the value of the form with the data that you're getting from your store. 您应该在ngOnInit设置表单,然后在其上调用patchValue方法以使用从商店中获取的数据来设置表单的值。

formGroup: FormGroup;

ngOnInit() {

  this.formGroup = new FormGroup({
    name: new FormControl(),
    content_type: new FormControl(),
    actual_content: new FormControl(),
    content_url: new FormControl(),
    additional_content: new FormControl(),
    media_type: new FormControl(),
    media_source: new FormControl(),
    language_id: new FormControl(),
    thumbnail: new FormControl(),
  });

  this.store.dispatch(new fromCourse.LoadCardDetails());

  this.actionsSubject$
    .pipe(filter(action => action.type === CourseActionTypes.LOAD_CARD_DETAILS_SUCCESS))
    .subscribe((data: {
      type,
      payload: ICardContent
    }) => {
      this.formGroup.patchValue(data.payload);
    });
}

get content_type() {
  return this.formGroup.get('content_type');
}
get name() {
  return this.formGroup.get('name');
}
get actual_content() {
  return this.formGroup.get('actual_content');
}
get content_url() {
  return this.formGroup.get('content_url');
}
get additional_content() {
  return this.formGroup.get('additional_content');
}
get media_type() {
  return this.formGroup.get('media_type');
}
get media_source() {
  return this.formGroup.get('media_source');
}
get language_id() {
  return this.formGroup.get('language_id');
}
get thumbnail() {
  return this.formGroup.get('thumbnail');
}

The problem is that your view needs the formGroup to render the html but that is null by default and only defined in the subscriber. 问题在于您的视图需要formGroup来呈现html,但是默认情况下为null,并且仅在订阅服务器中定义。

You better move the creation of the form to the constructor (use empty strings by default). 您最好将表单的创建移到构造函数中(默认情况下使用空字符串)。

     constructor(){
        this.formGroup = new FormGroup({
             name: new FormControl('', []),
             content_type: new FormControl(''),
             actual_content: new FormControl(''),
             content_url: new FormControl(''),
             additional_content: new 
                   FormControl(''),
             media_type: new FormControl(''),
             media_source: new FormControl(''),
             language_id: new FormControl(''),
             thumbnail: new FormControl(''),
      });

Then when the subscription is triggered patch the existing form with new data: 然后,当触发订阅时,使用新数据修补现有表单:

this.formGroup.get('content_type').patchValue(data.payload.content_type);

In this way the form always exists. 这样,表单始终存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从API为Angular 2动态表单设置值 - Setting Values From API for Angular 2 Dynamic Form 如何从angular2中的动态HTML获取表单值 - How to get form values from dynamic HTML In angular2 从 Angular 中的反应式 Forms 中的表单组中获取数组的值 - Get the values from array from Form Group in Reactive Forms in Angular 如何以动态角度形式获取更改事件的值? - how to get values on change event in dynamic angular forms? 如何从动态形式中获取价值 - how to get value from dynamic form in angular 角度2,动态形式; updateValue()不更新复选框表单控件 - Angular 2, dynamic forms; updateValue() do not update checkbox form control 角度动态形式:以编程方式更新值是一种不好的做法吗? - Angular dynamic forms: Is a bad practice to update values programmatically? 如何从mongodb将单选按钮值获取到编辑/更新表单? (Angular | Express | Nodejs | MongoDB) - How to get the radio button values from mongodb to the edit/update form? (Angular | Express | Nodejs | MongoDB) 如何从 FormArray 获取值 - Angular Reactive Forms - How to get values from FormArray - Angular Reactive Forms 如何从 angular 7 的 API 响应中制作动态形式? - how to make dynamic form from API response in angular 7?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM