0

I'm not having much luck in understanding angular. I have set up this simple test:https://stackblitz.com/edit/stackoverflow-q-54317647-ocxugf?file=app%2Fmy.component.spec.ts.

I set the component value input.value = "aaaa"; in the test and it shows up in the front end. If I change the value by typing a different text the value in the input component value does not seem to be updating.

2
  • you need to learn angular data binding approaches first, the simple test you mentioned shows that. for example you making event binding with disabled property (disabled) and that is wrong you need to use property binding instead with [disabled]. Commented Feb 2, 2019 at 6:35
  • 1
    if you want to use data binding with input the easiest way is two way data binding [(ngModel)] banana in the box that bind data from/to both sides Commented Feb 2, 2019 at 6:37

1 Answer 1

6

You need to use [(ngModel)] for two-way data binding.

<input [(ngModel)]="test" name="test" />

Now if you type any value in input your value will change in test variable. And if you want to have a predefined value in input field you can set the test variable value where you declared the variable like below.

test: string = 'aaa';

Here is an example

In ts file:

import { Component, OnInit, OnChanges, Input } from '@angular/core';


@Component({
  templateUrl: './my.component.html'
})

export class MyComponent implements OnInit {

  test: string;

  constructor() {}
  ngOnInit() {
  }

  printValue() {
    console.log(this.test);
  }
}

In HTML:

<input name="test" [(ngModel)]="test" id="test" />
<br/>
<button (click)="printValue()">Button</button>
Sign up to request clarification or add additional context in comments.

3 Comments

It did not work, I click on the button it still prints undefined in the console.
It works now : stackblitz.com/edit/…. I don't know why the previous example did not work.
Actually it cannot even start ;). So what is missing there? (For me no way works right now which should be a bug in VS Code or Angular itself...): Error: "Can't bind to 'ngModel' since it isn't a known property of 'input'"

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.