Angular 6 HTML选择菜单设置默认值 [英] Angular 6 HTML select menu set default value

查看:222
本文介绍了Angular 6 HTML选择菜单设置默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我习惯于使用较旧的angularjs方式进行选择菜单并选择默认值等,并且无法在Angular(6)中如何做到这一点。

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).

我有一系列菜单项:

  fontChoices = [
    {
      label: 'Trebuchet',
      value: "'Trebuchet MS', 'Helvetica Neue', Arial, sans-serif"
    },
    {
      label: 'Georgia',
      value: 'Georgia, times, serif'
    }
 ];

以及用于保存所选字体的变量: brandFont

and a variable to hold the chosen font: brandFont

我的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>

菜单有效,显示我的 fontChoices ,并改变选择激发我的功能。我可以选择Georgia或Trebuchet以及css变量更改和页面更新。

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.

  setStyle(e, which) {
    document.documentElement.style.setProperty(which, e);
  }

在页面加载时,css变量设置为Trebuchet。我可以在 ngOnInit 中获得

On page load, the css variable is set to Trebuchet. Which I can get in ngOnInit with

this.brandFont = String(styles.getPropertyValue('--font-family-brand')).trim();

我的问题是,如何让选择菜单显示第一个选择在页面加载?我已经尝试了 this.brandFont = this.fontChoices [0]; 但是菜单选中的项目是空的,直到从菜单中选择了某些内容。

My question is, how do I get the select menu to display this first choice on 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]

this.brandFont = this.fontChoices [0] .value;

https://angular-qlr8fj.stackblitz.io

这篇关于Angular 6 HTML选择菜单设置默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆