首页 > 解决方案 > 需要帮助传递用户输入数据以动态更改表单

问题描述

角度问题:我正在尝试获取用户下拉选择的值,以便动态填充下一个下拉列表并仅向他们显示应根据其原始选择返回的选项。我有一个函数,它获取 $event 的值,点击我的 JSON 文件,然后返回正确的字符串以填充下一个下拉列表,但唯一显示的是一个空下拉列表。

我抛出了虚拟 html 来测试 NgIf 并知道它的工作原理以及从我的函数返回的值,因为它们已经登录到控制台。在这里真的很茫然,除非我不知道幕后的角度,否则我应该能够将函数中的值插入 NgFor 并为第二个下拉列表抛出新创建的选项

post.component.ts:

export class PostComponent implements OnInit {
  rForm: FormGroup;
  title: String;
  description: String;
  category: String;
  subCategory: String;
  item: String;
  deathDate: Date;
  claimedBy: String;
  specifics: String;
  selections = postOptions;
  currentOptions: String[]
  showSecond: boolean = false
  showThird:boolean= false
  currentName:String


  toggleCategory(event) {


    this.showSecond = true
    let selectedTitle = (event.target.value);
    this.currentName = event.target.getAttribute('name')
    this.currentOptions = this.displaySubcategory(selectedTitle, 
    this.currentName);

  }

  displaySubcategory(str: any, dataToDisplay: String) {
      let childData = {
        index: 0,
        options: [],
      };

      for (let i = 0; i <= this.selections.length; i++) {
        if (str === this.selections[i].department) {
          childData.index = i;
          for 
            (let j = 0; j < this.selections[i].children.length; j++) 
             {
              childData.options.push
              (this.selections[i][`${dataToDisplay}`][j].title)
             }
        }
     return childData.options;
   }
}

post.component.html:

  <div class="panel-body">
    <div class="dropdown">
      <select class="form-control" id="category" 
      (change)="toggleCategory($event)" 
      [(ngModel)]="this.category" name="children">

        <option>scenery</option>
        <option>electrical</option>
        <option>material</option>
        <option>etc</option>

      </select>
    </div>

    <div *ngIf="this.showSecond">
      <div class="dropdown">
        <select class="form-control" id="category 
         (change)="toggleCategory($event)" 
         [(ngModel)]="currentOptions" name="item">
          <div *ngFor="let item of items">
            <option>{{item}}</option>
          </div>
        </select>
      </div>
    </div>

预期的结果被记录到控制台并存储为 this.currentOptions,NgIf 条件触发并呈现下一个下拉列表,但似乎没有任何内容传递给下拉列表。我需要异步设置一些东西吗?NgFor 是否在事件或 DOM 呈现时触发?

标签: angularformsngfor

解决方案


不要将你的包装<option>在一个div中。它应该是一个<ng-container>

    <select class="form-control" id="category 
     (change)="toggleCategory($event)" 
     [(ngModel)]="currentOptions" name="item">
      <ng-container *ngFor="let item of items">
        <option>{{item}}</option>
      </ng-container>
    </select>

推荐阅读