Acaeris
Acaeris

Reputation: 185

Angular2 binding on input doesn't seem to be working

I'm creating a component that changes an index based on the value selected from a dropdown. The dropdown itself is a stylised one rather than a native element and so updates a hidden input field. That field is in the template and has a binding with the variable in the component.

Here is the component and template:

import { Component, ElementRef, Input, OnInit } from '@angular/core';
import { Spell } from '../../models/spell';

/**
 * This class represents a Spell component
 */
@Component({
  moduleId: module.id,
  selector: 'ui-spell',
  templateUrl: 'spell.component.html',
  styleUrls: ['spell.component.css']
})
export class SpellComponent implements OnInit {
  @Input() spell: Spell;

  level: number;

  constructor(private el: ElementRef) {
    this.level = 1;
  }

  ngOnInit() {
  }

  update() {
    console.log(this.level);
  }
}

<div class="ui dropdown button">
  <input name="level" type="hidden" [(ngModel)]="level">
  <div class="text">Rank 1</div>
  <i class="dropdown icon"></i>
  <div class="menu">
    <div class="item" data-value="1">Rank 1</div>
    <div class="item" data-value="2">Rank 2</div>
    <div class="item" data-value="3">Rank 3</div>
    <div class="item" data-value="4">Rank 4</div>
    <div class="item" data-value="5">Rank 5</div>
  </div>
</div>
<button (click)="update()">Update</button>

The value of the input successfully changes but if I click on the Update button, the level still outputs as '1'. If I change the starting value in the component and inspect the input, the value has changed to match. There's no errors anywhere to explain why the value is not returned to the component. I have no idea where to look next.

Upvotes: 2

Views: 671

Answers (2)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657018

I'd use something like

<div class="item" (click)="level = 1" data-value="1">Rank 1</div>
<div class="item" (click)="level = 2" data-value="2">Rank 2</div>
<div class="item" (click)="level = 3" data-value="3">Rank 3</div>
<div class="item" (click)="level = 4" data-value="4">Rank 4</div>
<div class="item" (click)="level = 5" data-value="5">Rank 5</div>

Upvotes: 1

Dimitri Lavren&#252;k
Dimitri Lavren&#252;k

Reputation: 4879

You can only bind to objects in Angular as far as i know. Create an object with level as property and it should work. Vanilla JS syntax here:

var data = {level: 1};
//...

update() {
    console.log(this.level);
}

Bind to data.level:

<input name="level" type="hidden" [(ngModel)]="data.level">

Upvotes: 1

Related Questions