繁体   English   中英

ng-for 在 Angular 中生成的多选的默认选择值?

[英]Default selected value of an ng-for generated multi-select in Angular?

我需要为多选设置默认选定值。

我尝试初始化 ngModel 以绑定变量,并且还使用了[selected] = "selectedSegment == 'S1'" 他们都不为我工作

<select 
    class="form-control" 
    multiple 
    [(ngModel)]="selectedSegments" 
    name="segment_select"
    (change)="onChangeSegment()"
>
    <option *ngFor="let segment of segmentsToDisplay; let segIndex = index;" [ngValue]="segment">{{ segMap[segment] }}</option>
</select>

只需要将列表中的第一项作为默认选定值。

假设你有

segmentsTodisplay = [0, 1, 2];
segMap = ['a', 'b', 'c'];

设置很简单

selectedSegments = [0, 2];

然后将选择“a”、“c”。

您可以在索引上使用 selected 属性,但使用'selected' 作为值

<option [selected]="segIndex === 0 ? 'selected' : null "></option>

只需将您的 ngModel 设置为默认值。

假设 segmentToDisplay 有元素 = ['s1', 's2', 's3' ];

那么你的 ngModel 应该是 selectedSegments= ['s1'];

试试这个 - Angular 反应 forms 默认选择值设置

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

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
  blogForm: FormGroup;
  constructor(private fb: FormBuilder) {}

  Technology: any[] = [
    { ID: "1", Name: "Angular" },
    { ID: "2", Name: "Html" },
    { ID: "3", Name: "Nodejs" },
    { ID: "4", Name: "React" }
  ];

  DefaultSelectedArray: any[] = [
    { ID: "1", Name: "Angular" },
    { ID: "3", Name: "Nodejs" }
  ];

  ngOnInit() {
    this.isBuildForm();
    this.setDefaultValues();
  }

  setDefaultValues() {
    let valueArray = [];
    this.DefaultSelectedArray.forEach(element => {
      valueArray.push(element.ID);
    });
    this.blogForm.controls.Name.setValue(valueArray);
  }

  isBuildForm() {
    this.blogForm = this.fb.group({
      Name: ["", Validators.required]
    });
  }
}





<form [formGroup]="blogForm" (ngSubmit)="onSubmit(blogForm.value)" novalidate="novalidate" autocomplete="off">
    <select multiple class="form-control"  formControlName="Name">
       <option *ngFor="let option of Technology; let i = index" [value]="Technology[i].ID" [text]="Technology[i].Name" >
                {{ Technology[i].Name }}
        </option>
  </select>

</form>

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

结果 - 选定的值

暂无
暂无

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

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