如何在angular2中使用ng-select设置默认值?

时间:2017-03-22 19:09:57

标签: angular typescript

我的代码用html这样。

  <div class="col-md-10">
                <ng-select [items]="tests"
                           (data)="updateSelected($event, 'test')">
                </ng-select>
            </div>

我的打字稿代码如下

@Input()测试:Option [] = [];我将测试作为前一个组件的输入

 @ViewChildren(SelectComponent)
 private selectComponents: QueryList<SelectComponent>;

ngAfterViewInit() {
        this.selectComponents;
    }

如何在selectComponents中将某个值设置为默认值,或者使用ng-select将其他值设置为默认值。

3 个答案:

答案 0 :(得分:1)

使用如下的ngModel绑定。

<ng-select options="users" [(ngModel)]="selectedValue">
</select>
ngOnInit() {
  this.selectedValue = ["1"]
}

数组项值是选项ID。 https://basvandenberg.github.io/ng-select可能对您有所帮助。

答案 1 :(得分:0)

您必须为变量定义组件类型对象,或者您可以获取列表的第一个元素并将其设置为defualt变量。

    @ViewChildren(SelectComponent) private selectComponents: QueryList<SelectComponent>;
defualtComponent: any; ngAfterViewInit() { this.defaultComponent = this.selectComponents.get(0); }

这将选择第一个元素,如果这是你想要的ypur默认元素。

答案 2 :(得分:0)

For Reactive forms, you can bind the value while creating `FormGroup`.

在 TS 中:

 import { FormBuilder, Validators, FormGroup} from '@angular/forms';

 accountForm: FormGroup; // declaring form group


constructor(private fb: FormBuilder) {} 

ngOnInit(): void {
    this.createForm();
}

createForm(): void {
    this.accountForm = this.fb.group({
       trial: ['Yes', [Validators.required]] // Its default value
    });
  }

如果值是动态的(例如来自 API 调用),您可以使用 this.accountForm.patchValue({trial: 'abcd'});

在 HTML 中:

<form class="form"
    [formGroup]="accountForm"
    (ngSubmit)="onSubmit(accountForm)"
    autocomplete="off"
    novalidate>
    <div  class="form-row">
    <div class="col-sm-4" >
      <div class="form-group">
      <label>Trial</label>
      <ng-select
         [items]="booleanDropdown"
         [multiple]="false"
         [selectableGroup]="true"
         [closeOnSelect]="true"
         [clearable]="false"
         formControlName="trial">
      </ng-select>
      </div>
  </div>
</div>