繁体   English   中英

如何使用Reactive表单动态设置单选按钮文本? 并选择*单选按钮值和问题标题* onSubmit

[英]How to set radio button text dynamically using Reactive form? and and selected *radio button value and question title * onSubmit

我已经使用反应式表单数组动态添加了问题列表(2)和选项列表(3或4)。

问题1 )如何使用表单数组动态设置单选按钮文本

问题2)现在我试图只选择 问题Id onSubmit方法选择Id 我怎样才能做到这一点?

我试过下面粘贴的代码,请帮帮我。

export class HomeComponent implements OnInit {
  survey: FormGroup;
  user: User[] = [
    {
      id: 1,
      question: 'Question 1',
      choice: [
        {
          ChoceId: 1,
          Value: '1choice 1'
        },
        {
          ChoceId: 2,
          Value: '1choice 2'
        },
        {
          ChoceId: 3,
          Value: '1choice 3'
        },
        {
          ChoceId: 4,
          Value: '1choice 4'
        }

      ]
    }, {
      id: 2,
      question: 'Question 2',
      choice: [
        {
          ChoceId: 1,
          Value: '2choice 1'
        },
        {
          ChoceId: 2,
          Value: '2choice 2'
        },
        {
          ChoceId: 3,
          Value: '2choice 3'
        }
      ]
    }, {
      id: 3,
      question: 'Question 3',
      choice: [
        {
          ChoceId: 1,
          Value: '3choice 1'
        },
        {
          ChoceId: 2,
          Value: '3choice 2'
        },
        {
          ChoceId: 3,
          Value: '3choice 3'
        }
      ]
    }
    , {
      id: 4,
      question: 'Question 4',
      choice: [
        {
          ChoceId: 1,
          Value: '4choice 1'
        },
        {
          ChoceId: 2,
          Value: '4choice 2'
        },
        {
          ChoceId: 3,
          Value: '4choice 3'
        },
        {
          ChoceId: 4,
          Value: '4choice 4'
        }
      ]
    }
    , {
      id: 5,
      question: 'Question 5',
      choice: [
        {
          ChoceId: 1,
          Value: '5choice 1'
        },
        {
          ChoceId: 2,
          Value: '5choice 2'
        },
        {
          ChoceId: 3,
          Value: '5choice 3'
        },
        {
          ChoceId: 4,
          Value: '5choice 4'
        }
      ]
    },
    {
      id: 6,
      question: 'Question 6',
      choice: [
        {
          ChoceId: 1,
          Value: '6choice 1'
        },
        {
          ChoceId: 2,
          Value: '6choice 2'
        },
        {
          ChoceId: 3,
          Value: '6choice 3'
        },
        {
          ChoceId: 4,
          Value: '6choice 4'
        }
      ]
    },
    {
      id: 7,
      question: 'Question 7',
      choice: [
        {
          ChoceId: 1,
          Value: '7choice 1'
        },
        {
          ChoceId: 2,
          Value: '7choice 2'
        },
        {
          ChoceId: 3,
          Value: '7choice 3'
        },
        {
          ChoceId: 4,
          Value: '7choice 4'
        }
        ,
        {
          ChoceId: 5,
          Value: '7choice 4'
        }
      ]
    }
  ]

  constructor() {

  }

  ngOnInit() {


    this.survey = new FormGroup({
      sections: new FormArray([
        this.initSection(),
      ]),
    });

    for (let i = 0; i < this.user.length; i++) {

      this.addQuestion(0, this.user[i].question)
        this.add(0, i+1,this.user[i].choice);
        this.removeOption(0, i, 0)  
       }
    this.removeQuestion(0);
  }

  initSection() {
    return new FormGroup({
      questions: new FormArray([
        this.initQuestion('questionTitle')
      ])
    });
  }

  initQuestion(val: string) {
    return new FormGroup({
      questionTitle: new FormControl(val),
      options: new FormArray([
        this.initOptions('')
      ])
    });
  }

  initOptions(val: string) {
    return new FormGroup({
      optionTitle: new FormControl(val)
    });
  }

  addSection() {
    const control = <FormArray>this.survey.get('sections');
    control.push(this.initSection());
  }

  addQuestion(j, val: string) {
    console.log(j);
    const control = <FormArray>this.survey.get('sections').controls[j].get('questions');
    control.push(this.initQuestion(val));

  }

  add(i, j, choice: Choices[]) {

    const control = <FormArray>this.survey.get('sections').controls[i].get('questions').controls[j].get('options');
    if (choice) {
       for (j = i; j < choice.length; j++) {
        control.push(this.initOptions(choice[j] .Value));
      }
    }else{
      control.push(this.initOptions(''));
    }
  }

  getSections(form) {
    //console.log(form.get('sections').controls);
    return form.controls.sections.controls;
  }
  getQuestions(form) {
    //console.log(form.controls.questions.controls);
    return form.controls.questions.controls;
  }
  getOptions(form) {
    //console.log(form.get('options').controls);
    return form.controls.options.controls;

  }

  removeQuestion(j) {
    const control = <FormArray>this.survey.get('sections').controls[j].get('questions');
    control.removeAt(j);
  }

  removeSection(i) {
    const control = <FormArray>this.survey.get('sections');
    control.removeAt(i);

  }

  removeOption(i, j, k) {
    // debugger;
    console.log(i, j, k);
    const control = <FormArray>this.survey.get(['sections', i, 'questions', j, 'options']); // also try this new syntax
    control.removeAt(k);
  }

  remove(i, j) {
    const control = <FormArray>this.survey.get(['sections', i, 'questions', j, 'options']);
    control.removeAt(0);
    control.controls = [];
  }

  onSubmit(form:NgForm) {
    debugger;

    console.log(this.survey.value.optionTitle);
    console.log(form);

  }

}

这是我试过的HTML

<form [formGroup]="survey" novalidate (ngSubmit)="onSubmit(survey)">
    <!---Survey Section -->
    <div formArrayName="sections">
      <div class="section-container" *ngFor="let section of getSections(survey); let i = index">
        <div class="ui raised segments" [formGroupName]="i">
          <h4 class="ui header">User likes and choices</h4>
          <!-- <input type="text" placeholder="Untitled form" formControlName="sectionTitle">
          <input type="text" placeholder="Form Description" formControlName="sectionDescription"> -->
          <!-- Question segment -->
          <!---Survey Section -->
          <hr>
          <div class="question-container" formArrayName="questions">
            <div [formGroupName]="j" *ngFor="let question of getQuestions(section); let j = index">
              <input type="text" placeholder="Untitled Question" formControlName="questionTitle">
              <!-- <select formControlName="questionType">  
                          <option></option>
                            <option>Check Boxes</option>
                            <option>Free Text</option>
                            <option>Rating</option>
                            <option>Date</option>
                            <option>Time</option>
                        </select> -->

    <div *ngIf="survey.errors" class="alert alert-danger">
            {{ survey.errors }}
          </div>
             <div>
              <a (click)="add(i,j)">Add_Option</a>||
              <a (click)="remove(i,j)">Remove_whole_options</a>
            </div>
              <!-- Option Addation -->
              <div formArrayName="options">
                <div [formGroupName]="k" *ngFor="let option of getOptions(question); let k=index">

                   <input type="radio" id="{{ 'acceptable' + i}}" >
                  <input type="text" placeholder="Option 1" formControlName="optionTitle">


                  <!-- <a (click)="remove(i,j)">Option</a> -->
                  <span *ngIf="getOptions(question).length > 1" (click)="removeOption(i,j,k)">Remove_Option</span>
                </div>
                <!-- End Option Addition -->
                <!-- Option Addtion -->
                <!-- End Option Addition -->

              </div><br>
              <hr>
              <div>
              <a (click)="addQuestion(i)">Add Question...</a>
              <span *ngIf="getQuestions(section).length > 1" (click)="removeQuestion(i)">Remove Question</span>
            </div>
            </div><br>
          </div>
          <!-- End Question -->

        </div>
        <br>
        <button (click)="addSection()" class="point">Add Section </button>
        <span *ngIf="getSections(survey).length > 1" (click)="removeSection(i)">Remove Section</span>
      </div>
    </div>
    <!-- End Section -->
    <button type="submit">Get-Link</button>
  </form>

  <pre> {{survey.value | json}} </pre>

这是我的输出:

如果我理解你的问题。 为了填充单选按钮的值,动态使用下面的代码。

      dataSource = User[]; // you have to create a user class
      ngonInit() {
         this.populateUsers();
      }
        populateUsers() {
        this.dataSource = [];
        this.userService.getUserData().subscribe( resp => {
        resp.forEach(element => {
          console.log(element);
        const config = new  User(element.choiceId, element.Value); // User class have 
             constructor taking these values
          this.dataSource.push(config);
      });
     }

下面是下拉列表的示例,您可以对单选按钮执行类似操作

 <select  formControlName= "user"  class="form-control" 
                           (change)="selectUserOption($event.target.value);">
                             <option  [value]="d.value" *ngFor="let d of dataSource">
                                      {{d.ChoiceId}}
                                </option>
                          </select>

这是下拉列表的(更改)事件,然后您可以读取所选按钮的值。

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM