微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在 Angular Reactive Form 中制作带有评论区域的清单?

如何解决如何在 Angular Reactive Form 中制作带有评论区域的清单?

我正在处理交给我的一个简单任务,要求我创建一个“列表”或类似的任务,它显示 FormArray 中存在的“类别”,能够检查那些感兴趣的我,并添加在提交表单时写评论的机会,该评论将被批准或不批准该表单的人收到。

以下是应显示类别的网络图片

You can see there is an [object object] where I want the categories to be displayed

这是我的 .ts 中的代码

import { Component,OnInit,Inject } from '@angular/core';
import { MatDialogRef,MAT_DIALOG_DATA } from '@angular/material/dialog';
import { FormBuilder,FormGroup,Validators,FormArray,FormControl } from '@angular/forms';
import { ISubscription } from 'src/app/interfaces/Isubscription';
import { IUser } from 'src/app/interfaces/Iuser'
import { ICategory } from 'src/app/interfaces/Icategory';
import { IEvent } from 'src/app/interfaces/Ievent';
import { ISignupForm} from 'src/app/interfaces/IsignUpForm';
import { AuthService } from 'src/app/services/auth.service';
import { ISignupFormResponse } from 'src/app/interfaces/IsignUpFormResponse';
import { EventService } from 'src/app/services/event.service';
import { HttpResponse,HttpErrorResponse } from '@angular/common/http';
import { AppToastService } from 'src/app/services/toast.service';
import { browserModule } from '@angular/platform-browser';


@Component({
  selector: 'app-event-subscription-form',templateUrl: './event-subscription-form.component.html',styleUrls: ['./event-subscription-form.component.scss']
})
export class EventSubscriptionFormComponent implements OnInit {
 
  event: IEvent
  user: IUser
  loading: boolean = false;
  showCategories: boolean = false;
  selectedCategories: ICategory[] = [];
  requestSignupForm: ISignupForm;
  signUpFormResponse: ISignupFormResponse;
  selectedRole: string;
  subscription: ISubscription;
  categoriesComments: string[] = [];
  showtextarea: boolean = false;
  categoryCommentTitle: string;

  
  constructor(
    private eventService: EventService,private fb: FormBuilder,public authService: AuthService,private toastService: AppToastService,public dialogRef: MatDialogRef<EventSubscriptionFormComponent>,@Inject(MAT_DIALOG_DATA) public data: any
  ) { 
    this.event = data.event;
    //this.subscriptionForm.controls.event.setValue(this.event._id);
    this.subscriptionForm.patchValue({
      event: this.event._id
    });
    this.user = this.authService.currentUserValue;
  }

  subscriptionForm: FormGroup = this.fb.group({
    event: [null,Validators.required],user: [null,role: [null,status: [null],categories: this.fb.array([])
  })

  
  ngOnInit(): void {
    this.subscriptionForm.patchValue({
      user: this.user._id
    });
    this.subscriptionForm.get('categories')

  }

  category = new FormArray([
    this.subscriptionForm.get('categories') as FormArray
  ]);

  get items(): FormArray{
    return this.subscriptionForm.get('signUpForm.items') as FormArray;
  }

  
  onRadioChange() {
    this.showCategories = true;
    this.selectedRole = this.subscriptionForm.get('role').value;
    
    this.requestSignupForm = this.getFormByRole(this.selectedRole);
    console.log(this.requestSignupForm);
    
    if (!this.requestSignupForm) {
      this.subscriptionForm.removeControl('signUpForm');
      return;  
    }
    
    this.subscriptionForm.addControl('signUpForm',this.fb.group({
      items: this.fb.array([]),translations: this.fb.group({
        en: this.fb.group({
          title: [null,description: [null]
        }),es: this.fb.group({
          title: [null,description: [null]
        })
      })
    }));

    this.subscriptionForm.patchValue(
      {signUpForm: {
        role: this.selectedRole,translations: this.requestSignupForm.translations
      }}
    );
   
    this.requestSignupForm.items.forEach(item => {
      const formItem: FormGroup = this.fb.group({
        position: [-1,type: ['',translations: this.fb.group({
          es: this.fb.group({
            label: [null,choices: [null]
          }),en: this.fb.group({
            label: [null,choices: [null]
          })        
        }),response: [null,checked: [false]
      });

      formItem.patchValue(item);
      formItem.patchValue({type: 'text'});
      this.items.push(formItem);

      console.log(this.subscriptionForm.value);
      
    });
  }

  
  getFormByRole(role: string): ISignupForm | null {
    const form: ISignupForm | undefined = this.event.signupForms.find(
      (form: ISignupForm) => {
        return form.role === role;
      }
      );
      if (typeof form === 'undefined') {
        return null;
      }
      return form;
  }

  addCategory(newCategory: ICategory) {
      this.selectedCategories.push(newCategory);
    }

  saveComment(comment: string){
    this.categoriesComments.push(comment);
    this.showtextarea = false;
  }

  removeCategory(index: number) {
    this.selectedCategories.splice(index,1);
    this.categoriesComments.splice(index,1);
  }


  onSubmit() {
    this.loading = true;
    
    
    this.subscription = this.subscriptionForm.value;
    console.log(this.subscription);
    

    this.eventService.addSubscription(this.event._id,this.subscription).subscribe(
      (resp: HttpResponse<any>) => {
        this.toastService.show('COMPONENTS.FORMS.SUBSCRIPTION.SUBSCRIPTION_SUCCESSFUL','success');
        this.loading = false;
        this.dialogRef.close('reload');
      },(err: HttpErrorResponse) => {
        console.log(err);
        this.toastService.show('COMPONENTS.FORMS.SUBSCRIPTION.SUBSCRIPTION_Failed','danger');
        this.loading = false;
      }
    );
     
  } 

}

以及我的 .html 中的模板:

<div mat-dialog-content>
  <mat-card class="form-section-card">
    <mat-card-title>          
      {{ 'COMPONENTS.FORMS.SUBSCRIPTION.FORM_TITLE' | translate }}                   
    </mat-card-title>
    <mat-card-content>
      <form [formGroup]="subscriptionForm" class="modal-form" novalidate>
        <div *ngIf="loading" class="overlay-spinner"><mat-spinner></mat-spinner></div>

        <!-- ROLE SELECTION -->
        <mat-card-subtitle id="choose-role-label">{{'COMPONENTS.FORMS.SUBSCRIPTION.SELECT_ROLE' | translate}}</mat-card-subtitle><br>
        
        <mat-radio-group 
          aria-labelledby="choose-role-label"
          formControlName="role"
          (change)="onRadioChange()">
          <mat-radio-button value="buyer" class="radioBtn">{{'COMPONENTS.FORMS.SUBSCRIPTION.BUYER' | translate}}</mat-radio-button>
          <mat-radio-button value="exhibitor" class="radioBtn">{{'COMPONENTS.FORMS.SUBSCRIPTION.EXHIBITOR' | translate}}</mat-radio-button>
        </mat-radio-group>
        <p></p>
        

        <!-- CATEGORIES SELECTION -->
        <section *ngIf="showCategories">
          <mat-divider></mat-divider><br>
          <mat-card-subtitle id="choose-category-label">{{'COMPONENTS.FORMS.SUBSCRIPTION.SELECT_CATEGORIES' | translate}}</mat-card-subtitle>

          <mat-list>
            <mat-list-item ngForm="let category of categories">
              <p matLine>
                <span> {{category}} </span>
                <span class="demo-2"> -- {{categoriesComments}} </span>
              </p>
            </mat-list-item>
          </mat-list>
          
          <!-- three line list -->
          <mat-list>
            <mat-list-item *ngFor="let category of categoriesComments">
              <p matLine> {{categoriesComments}} </p>
              <p matLine class="demo-2"> {{categoriesComments}} </p>
            </mat-list-item>
          </mat-list>

          <!-- Categorias Seleccionadas
          <mat-card *ngIf="showtextarea">
            <mat-card-subtitle>
              {{ 'COMPONENTS.FORMS.SUBSCRIPTION.ADD_COMMENT' | translate }} {{ categoryCommentTitle }}
            </mat-card-subtitle>
            <mat-card-content class="pos-relative">
              <textarea 
                class="full-width"
                #comment
                autofocus="true"
                ></textarea>
              <mat-card-actions class="full-width">
                <button
                  button 
                  mat-raised-button 
                  color="accent"
                  (click)="saveComment(comment.value)">
                  {{ 'COMPONENTS.FORMS.SUBSCRIPTION.CONFIRM' | translate }}
                </button>
              </mat-card-actions>
            </mat-card-content>
          </mat-card>
        

          <mat-card style="margin: 12px 0;">
            <mat-card-header>
              <mat-card-subtitle>{{ 'COMPONENTS.FORMS.EVENT.LABELS.SELECTED_CATEGORIES' | translate }}</mat-card-subtitle>
            </mat-card-header>
            <mat-list *ngIf="!showtextarea">
              <mat-list-item
                *ngFor="let cat of selectedCategories; let i=index"
                class="flex-list-item"
              >
                <span>{{ cat.translations[authService.currentUserValue.language].name }}</span>
                <textarea 
                  *ngIf="categoriesComments[i].length > 0"
                  disabled="true" 
                  [title]="'COMPONENTS.FORMS.SUBSCRIPTION.COMMENTS' | translate">{{ categoriesComments[i] }}</textarea>  
                <button
                  mat-icon-button
                  color="warn"
                  (click)="removeCategory(i)"
                >
                  <mat-icon>delete</mat-icon>
                </button>
              </mat-list-item>
      
              <mat-list-item *ngIf="selectedCategories.length === 0">
                {{ 'COMPONENTS.FORMS.EVENT.LABELS.NO_SELECTED_CATEGORIES' | translate }}
              </mat-list-item>
            </mat-list>
          </mat-card>
        -->
          
        <!-- SIGNUP FORM -->
          <ng-container *ngIf="requestSignupForm">
            <mat-card-subtitle>
              {{requestSignupForm.translations[authService.currentUserValue.language].title}}
            </mat-card-subtitle>
            <div formGroupName="signUpForm">
              <div formArrayName="items">
                <mat-list *ngFor="let item of requestSignupForm.items; let i=index">
                  <mat-form-field [formGroupName]="i" class="full-width">
                    <mat-label>
                      {{requestSignupForm.items[i].translations[authService.currentUserValue.language].label}}
                    </mat-label>
                    <textarea 
                      formControlName="response" 
                      matInput>
                    </textarea>
                  </mat-form-field>
                </mat-list>
              </div>
            </div>
          </ng-container>

        </section>
        
        <mat-card-actions  align="end">
          <button
            [disabled]="!subscriptionForm.valid || selectedCategories.length == 0"
            mat-flat-button
            type="submit"
            color="primary"
            (click)="onSubmit()"            
            >
            {{ 'GENERIC.ACTIONS.ACCEPT' | translate }}
          </button>
        </mat-card-actions>
      </form>
    </mat-card-content>
  </mat-card>
</div>

我知道我一定是做错了,我正在学习 FormArray 和 FormGroups 以帮助自己完成任务,但它变得越来越困难,因为项目已经基本建成,而且我在网上找到的例子非常简单。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。