10

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

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

My html menu is

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

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

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();

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.

0

2 Answers 2

6

Just change your one statement

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

https://angular-qlr8fj.stackblitz.io

Sign up to request clarification or add additional context in comments.

Comments

4

Use an option with the first value like this <option [value]="defaultFont.label" selected="selected">{{defaultFont.label}}</option>

Component 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

  brandFont: any; 
  defaultFont: any;

  ngOnInit() {
    this.defaultFont = this.fontChoices[0];
    this.brandFont = Object.assign(this.defaultFont.label);
  }

Here is a demo stackblitz

3 Comments

That gives me 2 Trebuchets, and choosing an item from the menu makes it go blank. Even on the Stackblitz
That fixed the duplicate, but after choosing an item on the menu the menu selected item is empty. And then if you open the menu again, Trebuchet is gone. see jmp.sh/dSAPrFS
Actually, the answer @rohit.007 below works perfectly, just by adding 6 characters to what I had.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.