fastcodejava
fastcodejava

Reputation: 41097

Binding an input to component in angular

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.

Upvotes: 0

Views: 6141

Answers (1)

Balaj Khan
Balaj Khan

Reputation: 2570

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>

Upvotes: 4

Related Questions