ttmt
ttmt

Reputation: 4984

Angular2 one way databinding in input field

Very simple, I have a component containing a string

I need to show this string in an input field.

I thought I need it like this but it doesn't work.

import {Component} from "@angular/core";

@Component({
    selector: 'my-component',
    template: `
        <input type="text" ([ngModel])="myVar" >
    `
})

export class MyComponent{

  constructor(){
  } 

  myVar: string = "Hello World"

}

Upvotes: 0

Views: 5850

Answers (2)

Chandru
Chandru

Reputation: 11182

Solution is :

([ngModel])="myVar" => [(ngModel)]="myVar"

add name field in input type name="myVar"

Try Like this :

import { Component } from "@angular/core";

@Component({
    selector: 'my-component',
    templateUrl: './my-compoent.template.html';
})
export class MyComponent {
    myVar: string = "Hello World"
    constructor() { }
}

in html you need to add name in input type

<input type="text" name="myVar" [(ngModel)]="myVar" >

Upvotes: 2

Lazar Ljubenović
Lazar Ljubenović

Reputation: 19764

([ngModel]) syntax is wrong, it should be [(ngModel)]. Notice the order of parans.

Mnemonic is banana in the box. [ looks like a box and ( looks like a banana.


Also you seem to have a typo in the path to your template file, it says ./my-compoent instead of ./my-component which is what the file is probably named.

Upvotes: 3

Related Questions