You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 5表单显隐异常:选中LG/JAMES无法展示对应内容

Hey there! Let's sort out that visibility logic issue you're facing with your Angular 5 reactive form. I notice you mentioned you intended to use template-driven forms but ended up with reactive ones—no problem, we can get this working perfectly with the setup you already have.

What's Going Wrong

The main issue is that your template is trying to reference type and person variables directly, but in a reactive form, these values are stored inside your salesForm FormGroup. The template can't find those standalone variables, so the *ngIf conditions never trigger as expected. Also, your checkbox setup has a small problem: binding multiple checkboxes to a single FormControl will overwrite the value each time a different box is checked, so we'll fix that too.

Fixed Solution

First, let's update the component to handle checkboxes properly and add helper getters to make the template cleaner:

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, FormControl, FormArray } from '@angular/forms';

export class SalesComponent implements OnInit {
  salesForm: FormGroup;

  constructor(private formBuild: FormBuilder) {}

  ngOnInit() {
    this.salesForm = this.formBuild.group({
      type: new FormControl(),
      // Use FormArray to track multiple selected checkboxes
      person: this.formBuild.array([])
    });
  }

  // Helper getter for easy access to the type control
  get typeControl() {
    return this.salesForm.get('type');
  }

  // Helper getter to treat person as a FormArray
  get personArray() {
    return this.salesForm.get('person') as FormArray;
  }

  // Check if JAMES is selected in the person array
  isJamesSelected() {
    return this.personArray.value.includes('JAMES');
  }
}

Now update the template to use the reactive form values correctly, and fix the checkbox binding:

<form novalidate [formGroup]="salesForm">
  <div class="row">
    <div class="col-md-4">
      <div class="form-group">
        <label>MOBILE PHONES</label>
        <div class="radio">
          <label><input type="radio" formControlName="type" name="type" value="LG">LG</label>
          <label><input type="radio" formControlName="type" name="type" value="HTC">HTC</label>
        </div>
        <legend>PEOPLE</legend>
        <div class="checkbox">
          <label>
            <input type="checkbox" 
                   [value]="'JAMES'" 
                   (change)="$event.target.checked ? personArray.push(new FormControl('JAMES')) : personArray.removeAt(personArray.value.indexOf('JAMES'))">
            JAMES
          </label>
          <label>
            <input type="checkbox" 
                   [value]="'JOHN'" 
                   (change)="$event.target.checked ? personArray.push(new FormControl('JOHN')) : personArray.removeAt(personArray.value.indexOf('JOHN'))">
            JOHN
          </label>
        </div>
      </div>
    </div>
    <div class="col-md-4">
      <!-- Show HTC RESULT when LG radio is selected (matches your requirement) -->
      <div *ngIf="typeControl.value === 'LG'" class="form-group">
        <h1>HTC RESULT PHONES</h1>
      </div>
      <!-- Show JAMES RESULT when JAMES checkbox is checked -->
      <div *ngIf="isJamesSelected()" class="form-group">
        <h1>JAMES RESULT</h1>
      </div>
    </div>
  </div>
</form>

Key Changes Explained

  1. FormArray for Checkboxes: Switched person from a single FormControl to a FormArray so we can track multiple selected values without overwriting.
  2. Helper Getters: Added typeControl and personArray to make accessing form values in the template cleaner and more readable.
  3. Checkbox Binding: Updated checkboxes to add/remove values from the FormArray on change, ensuring all selections are tracked.
  4. Corrected *ngIf Conditions: Now references the actual form control values from the reactive form, so the visibility logic triggers correctly based on user input.

Note: If you actually meant to show the HTC result when the HTC radio is selected (instead of LG), just change typeControl.value === 'LG' to typeControl.value === 'HTC' in the template.

内容的提问来源于stack exchange,提问作者Anele

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:54:40