0

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"

}
4
  • Use [(ngModel)]="myVar" (or [ngModel]="myVar" if it is just 1-way binding) Commented Sep 26, 2017 at 15:11
  • True your ngModel syntax is wrong Commented Sep 26, 2017 at 15:13
  • 1
    [ngModel]="myVar" doesn't work Commented Sep 26, 2017 at 15:15
  • @ttmt you don't need name attribute unless you use this input as a template driven formControl (not mentioned in the original OP). For implementing the binding between the input field and the component property just the right 'banana-in-a-box' syntax should suffice. See this to learn more on implementing 2-way bindings. Also, like I mentioned, [ngModel] is just 1-way binding - meaning it will populate the value once from the component to the view on initial load. Commented Sep 26, 2017 at 15:30

2 Answers 2

4

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

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

Comments

3

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

4 Comments

Thank you, it was the name I was missing.
Name shouldn't have anything to do with this, it was the order of parans for the two-way data-binding that fixed it.
That was a typo sorry, it was the name that fixed it for me.
Isn't this 2 way binding?

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.