如何在反应形式内的 ng-select 中设置默认值
how to set a default value in a ng-select inside a reactive form
你好,我正在尝试在我的 angular 反应式表单中使用 ng-select,我刚刚完成了它的工作,但我无法设置默认值(示例 Male) 在ng-select,我该怎么做?
HTML
<form [formGroup]="demographyForm">
<section class="form-group">
<h2 class="card-body__content--title">{{ labels[0] }}</h2>
<ng-select
style="max-width: 130px;"
formControlName="gender"
[clearable]="false"
[searchable]="false"
[virtualScroll]="true">
<ng-option [value]="">Gender</ng-option>
<ng-option *ngFor="let gender of genders" [value]="gender">{{gender}}
</ng-option>
</ng-select>
</section>
</form>
TS
genders: string[] = ['Male', 'Female'];
constructor(private fb: FormBuilder) {}
demographyForm = this.fb.group({
gender: ['', [Validators.required]]})
get gender() {
return this.demographyForm.get('gender');
}
可以在fb里面设置默认值
import { Component, VERSION } from '@angular/core';
import { FormBuilder } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
constructor(private fb: FormBuilder) {}
labels: string[] = ['Gender', 'Civil Status', 'Age Range'];
genders: string[] = ['Male', 'Female'];
demographyForm = this.fb.group({
gender: ['Male'],
});
}
你好,我正在尝试在我的 angular 反应式表单中使用 ng-select,我刚刚完成了它的工作,但我无法设置默认值(示例 Male) 在ng-select,我该怎么做?
HTML
<form [formGroup]="demographyForm">
<section class="form-group">
<h2 class="card-body__content--title">{{ labels[0] }}</h2>
<ng-select
style="max-width: 130px;"
formControlName="gender"
[clearable]="false"
[searchable]="false"
[virtualScroll]="true">
<ng-option [value]="">Gender</ng-option>
<ng-option *ngFor="let gender of genders" [value]="gender">{{gender}}
</ng-option>
</ng-select>
</section>
</form>
TS
genders: string[] = ['Male', 'Female'];
constructor(private fb: FormBuilder) {}
demographyForm = this.fb.group({
gender: ['', [Validators.required]]})
get gender() {
return this.demographyForm.get('gender');
}
可以在fb里面设置默认值
import { Component, VERSION } from '@angular/core';
import { FormBuilder } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
constructor(private fb: FormBuilder) {}
labels: string[] = ['Gender', 'Civil Status', 'Age Range'];
genders: string[] = ['Male', 'Female'];
demographyForm = this.fb.group({
gender: ['Male'],
});
}