簡體   English   中英

如何在 Angular 反應形式中的 mat-checkbox 或 mat-radio-button 之間切換?

[英]How can I toggle between mat-checkbox or mat-radio-button in Angular reactive form?

我正在創建一個測驗應用程序,需要在 mat-checkbox 或 mat-radio-button 之間切換,具體取決於問題是否有一個或多個答案。 問題 #1 是單選答案問題,使用 mat-radio-button 顯示,而問題 #2 是多選問題,但也使用 mat-radio-button 而不是 mat-checkbox 顯示。

這是我的模板的樣子:

<form [formGroup]="formGroup">
    <ol *ngIf="multipleAnswer === false">
        // using mat-radio-buttons here 
    </ol>
    <ol *ngIf="multipleAnswer === true">
        // using mat-checkboxes here
    </ol>
</form>

在我的 ts 文件中,邏輯如下所示:

multipleAnswer: boolean;

ngOnInit() {
  this.multipleAnswer = this.quizService.getQuestionType();
}

ngOnChanges(changes: SimpleChanges) {
  if (changes.question) {
    switch (this.question.type) {
      case 'SINGLE_CHOICE':
        this.formGroup = new FormGroup({
          answer: new FormControl([null, Validators.required])
        });
        break;
      case 'MULTIPLE_CHOICE':
        const multipleChoiceValidator = (control: AbstractControl) =>
          control.value.reduce(
            (valid: boolean, currentValue: boolean) => valid || currentValue
            , false
          ) ? null : {answers: 'At least one answer needs to be checked!'};
        this.formGroup = new FormGroup({
          answers: this.formBuilder.array(this.question.shuffledAnswers
              .map((answer: string) => this.formBuilder.control(false)),
            multipleChoiceValidator
          ),
        });
        break;
    }
  }
}

不需要 shuffledAnswers,問題類型應該從 assets/quiz.ts 文件中推斷出來(不需要硬編碼問題類型),答案應該是數字,而不是字符串

在我的測驗服務中:

getQuestionType(): boolean {
  return (this.correctAnswers && this.correctAnswers.length === 1);
}

有幾個問題。 首先,僅在ngOnInit內部調用multipleAnswer只會在開始時設置此 boolean 變量一次,它應該在ngOnChanges內部。

但這不是這里唯一的問題,主要問題在於您的QuizService 這里你使用this.quizService.getQuestionType(); 設置multipleAnswer true 或 false 的方法,但是在 QuizService 的getQuestionType()方法中,您正在檢查this.correctAnswers是否已設置並且元素長度為 1 但this.correctAnswers在您調用它時始終為空。

另一個問題是在你的ngOnChanges中你有switch (this.question.type)這里this.question似乎永遠是未定義的。

像下面這樣編輯您的代碼,並在每次出現問題時檢查控制台輸出。

添加一個從問題中獲取correctAnswers的新方法。

getCorrectAnswers(question:QuizQuestion){
   return question.options.filter((item)=> item.correct);
}

並像下面這樣編輯 ngOnChanges 的開頭,我還添加了一個控制台 output 以便您可以從上面的新方法中看到數據。

ngOnChanges(changes: SimpleChanges) {   
   if (changes.question && changes.question.currentValue !== changes.question.firstChange){
     this.currentQuestion = changes.question.currentValue;
     this.correctAnswers = this.getCorrectAnswers(this.currentQuestion);
     this.multipleAnswer = this.correctAnswers.length > 1 ? true : false;
     console.log('correct ans: ', this.correctAnswers);
     ...

我無法修改所有代碼,因為您的代碼背后有自己的邏輯,但我更新了答案,以便與此問題相關的變量在“ngOnChanges”中正確設置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM