Pet*_*ter 3 angular-material2 angular
给定以下使用 mat-select 的 Angular 组件
export enum AllValues {
VALUE_A = "A",
VALUE_B = "B",
VALUE_C = "C",
}
@Component({
selector: 'my-app',
template: `
<mat-form-field>
<mat-select ([ngModel])="myValue">
<mat-option *ngFor="let o of valueOptions" value="{{o}}">{{o}}</mat-option>
</mat-select>
</mat-form-field>
<p> Selected value: {{myValue}} </p>
`,
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
myValue: AllValues = AllValues.VALUE_B;
valueOptions = Object.keys(AllValues);
}
Run Code Online (Sandbox Code Playgroud)
如何让 myValue 的初始值显示在 UI 的 mat-select 中?该值未随代码的当前状态一起显示。
请点击此 StackBlitz 链接获取完整代码和正在运行的演示。
问题 :
这里的ngModel值和select选项值都是不同的,这就是您没有获得选定值的原因
组件侧:
// add this line
allValues = AllValues;
Run Code Online (Sandbox Code Playgroud)
模板面:
// Change ([ngModel]) to [(ngModel)]
<mat-select [(ngModel)]="myValue">
// value={{o}} to value="{{allValues[o]}}"
<mat-option *ngFor="let o of valueOptions" value="{{allValues[o]}}">{{o}}</mat-option>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11344 次 |
| 最近记录: |