Javascript Angular 6 HTML 选择菜单设置默认值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51047822/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular 6 HTML select menu set default value
提问by Steve
I'm used to the older angularjs way of doing select menus and selecting the default value etc and am having trouble wrapping my head around how to do this in Angular (6).
我习惯于使用较旧的 angularjs 方式进行选择菜单和选择默认值等,并且在 Angular (6) 中无法理解如何执行此操作。
I have a an array of menu items:
我有一系列菜单项:
fontChoices = [
{
label: 'Trebuchet',
value: "'Trebuchet MS', 'Helvetica Neue', Arial, sans-serif"
},
{
label: 'Georgia',
value: 'Georgia, times, serif'
}
];
and a variable to hold the chosen font: brandFont
和一个变量来保存所选字体: brandFont
My html menu is
我的 html 菜单是
<select [(ngModel)]="brandFont"
id="brandFontmenu"
(ngModelChange)="setStyle($event,'--font-family-brand')">
<option *ngFor="let font of fontChoices"
[value]="font.value">{{font.label}}
</option>
</select>
The menu works, displays my fontChoices, and changing the selection fires my function. I can choose Georgia or Trebuchet and the css variable changes and the page updates as it should.
菜单有效,显示 my fontChoices,更改选择会触发我的功能。我可以选择 Georgia 或 Trebuchet,并且 css 变量会发生变化并且页面会更新。
setStyle(e, which) {
document.documentElement.style.setProperty(which, e);
}
On page load, the css variable is set to Trebuchet. Which I can get in ngOnInitwith
在页面加载时,css 变量设置为 Trebuchet。我可以ngOnInit加入
this.brandFont = String(styles.getPropertyValue('--font-family-brand')).trim();
My question is, how do I get the select menu to display this first choiceon page load? I have tried this.brandFont = this.fontChoices[0];but the menu selected item is empty until something is chosen from the menu.
我的问题是,如何让选择菜单在页面加载时显示这个第一选择?我已经尝试过,this.brandFont = this.fontChoices[0];但是在从菜单中选择某些内容之前,菜单所选项目是空的。
采纳答案by Rohit.007
Just change your one statement
只需更改您的一项声明
this.brandFont = this.fontChoices[0]to
this.brandFont = this.fontChoices[0].value;
this.brandFont = this.fontChoices[0]到
this.brandFont = this.fontChoices[0].value;
回答by Abel Valdez
Use an option with the first value like this <option [value]="defaultFont.label" selected="selected">{{defaultFont.label}}</option>
像这样使用带有第一个值的选项 <option [value]="defaultFont.label" selected="selected">{{defaultFont.label}}</option>
Component HTML
组件 HTML
<select [(ngModel)]="brandFont"
id="brandFontmenu"
>
<option [value]="defaultFont.label" selected="selected">{{defaultFont.label}}
</option>
<option *ngFor="let font of fontChoices.slice(1)"
[value]="font.label">{{font.label}}
</option>
</select>
Component ts
组件 ts
brandFont: any;
defaultFont: any;
ngOnInit() {
this.defaultFont = this.fontChoices[0];
this.brandFont = Object.assign(this.defaultFont.label);
}
Here is a demo stackblitz
这是一个演示 stackblitz

