您可以使用 Angular Reactive Form 中的 FormControl。这很简单。
Angular Docs About Reactive Form
您需要将reactive form 导入到您的模块中
import { ReactiveFormsModule } from '@angular/forms';
@NgModule({
imports: [
// other imports ...
ReactiveFormsModule
],
})
export class AppModule { }
比你需要在你的 component.ts 中创建 FormControl
import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';
@Component({
selector: 'app-name-editor',
templateUrl: './name-editor.component.html',
styleUrls: ['./name-editor.component.css']
})
export class NameEditorComponent {
name = new FormControl('');
}
在此之后,您需要在 html 中将表单控件设置为您的元素 select
<select [formControl]="name">
<option value="null">No Default Layout</option>
<option *ngFor="let l of availableLayouts" [value]="l.id">
{{l?.name}}
</option>
</select>
如果您需要选择的默认值,您必须使用值创建 formControl,例如:
import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';
@Component({
selector: 'app-name-editor',
templateUrl: './name-editor.component.html',
styleUrls: ['./name-editor.component.css']
})
export class NameEditorComponent {
name = new FormControl(null);
}
///(you can pass any to new FormControl(0), or new FormControl(false), new FormControl('string'))
在这种情况下,select 的默认值为 null。并且值为 null 的选项将在 dropdawn 中被选中。
在你的情况下 new FormControl(0) 作为默认值。