简体   繁体   English

如何在动态选择组件角度中的选择上设置默认值

[英]How to set default value on select in a dynamic select component angular

I am trying to create a dynamic select component for my application. 我正在尝试为我的应用程序创建一个动态select组件。 This component would be used in various forms throughout my application. 在整个应用程序中,将以各种形式使用此组件。 In some cases, there may be some predefined value that may be provided to the select , in which case the value would be selected as default by the drop-down. 在某些情况下,可能会有一些预定义的值可以提供给select ,在这种情况下,下拉列表会将值选择为默认值。 In order to achieve this functionality I have looked over SO and found various questions that answer this problem, but are using NgModule as a directive for adding default value, whereas I am using formControlName for my component. 为了实现此功能,我查看了SO并找到了可以解决此问题的各种问题,但是我使用NgModule作为添加默认值的指令,而我正在为组件使用formControlName I have tried a solution myself (code added below) but it doesn't seem to be working. 我自己尝试了一种解决方案(下面添加了代码),但似乎没有用。 I am reluctant to use ngModule with formControlName because the feature is deprecated in Angular 6 (the version I am using). 我不愿意将ngModuleformControlName一起使用,因为该功能已在Angular 6(我使用的版本)中弃用。 How do I achieve the functionality? 如何实现功能?

component.html component.html

<div [formGroup]="group">
  <select id="{{ id }}" formControlName="{{ formControlName }}" class="form-control">
      <option value="" disabled selected>{{placeholder}}</option>
      <option *ngFor="let item of data" [ngValue]="item.id">{{item.name}}</option>
  </select>
</div>

component.ts component.ts

import { Component, ViewEncapsulation, Input } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';

@Component({
  selector: 'app-dropdown',
  templateUrl: './dropdown.component.html',
  styleUrls: ['./dropdown.component.scss'],
  encapsulation: ViewEncapsulation.None
})
/**
* This class is used to create a generic dropdown component. Population is done on runtime
*/
export class DropdownComponent{
  /**
  * Define FormGroup
  */
  @Input() group: FormGroup;

  /**
  * Define formControlName
  */
  @Input() formControlName: string;

  /**
  * Define id
  */
  @Input() id: string;

  /**
  * Define data
  */
  @Input() data: any;

  /**
  * Define placeholder
  */
  @Input() placeholder: string;

  /**
  * For any predefined value being passed
  */
  @Input() predefined: string;

  constructor() { }

}

what I tried (ts file remained the same) 我尝试了什么(ts文件保持不变)

<div [formGroup]="group">
  <select id="{{ id }}" formControlName="{{ formControlName }}" class="form-control">
    <ng-template *ngIf="predefined !== undefined; else default">
      <option *ngFor="let item of data" [selected]="item.id === predefined">{{item.name}}</option>
    </ng-template>
    <ng-template #default>
      <option value="" disabled selected>{{placeholder}}</option>
      <option *ngFor="let item of data" [ngValue]="item.id">{{item.name}}</option>
    </ng-template>
  </select>
</div>

In order to cater the problem, the solution was to define a method in the OnInit lifecycle hook, which extracted the entire object an inserted into the template. 为了解决该问题,解决方案是在OnInit生命周期挂钩中定义一个方法,该方法将整个对象提取并插入到模板中。 The lifecycle hook sets a particular variable called selection and sets to the formControl : 生命周期挂钩设置了一个名为selection的特定变量,并设置为formControl

selection: any

ngOnInit() {
    if (this.predefined !== undefined) {
      let index = Object.keys(this.data);
      var self = this;
      index.forEach(function(i) {
        Object.keys(self.data[i]).some(function(k) {
          if (self.data[i][k] === self.predefined) {
            self.selection = self.data[i];
            return self.data[i][k];
          }
        }
        )
      });
      this.group.controls[this.formControlName].setValue(this.selection.id, { onlySelf: true });
    }
  }

The template didn't need any modification like I did in the question's update, so reverted to the previous: 模板不需要进行任何修改,就像我在问题的更新中所做的那样,因此恢复为之前的版本:

<div [formGroup]="group">
  <select id="{{ id }}" formControlName="{{ formControlName }}" class="form-control">
      <option value="" disabled selected>{{placeholder}}</option>
      <option *ngFor="let item of data" [(ngValue)]="item.id">{{item.name}}</option>
  </select>
</div>

So if you want to provide any default values to the select statement you can do something like below, 因此,如果您想为select语句提供任何默认值,则可以执行以下操作,

Let's say I have this array of object in .ts 假设我在.ts中有这个对象数组

 Sports = [
 {
    "name": "running",
    "value" : "0"
 },
 {
    "name": "triathlon",
    "value" : "1"
 }
]

You can set the default value for the select statement in html like below, 您可以像下面这样在html中为select语句设置默认值,

<select class="form-control" (change)="get($event.target.value)">
   <option [value]="null" hidden>
      Select
   </option>
   <option *ngFor="let sport of Sports" [value]="sport.value">
      {{sport.name}}
   </option>
</select>

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

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