0

I have the following in my component.ts file:

@Component({
  selector: 'app-loop-back',
  template: `
    <input #box (keyup)="0">
    <p>{{box.value}}</p>
  `
})
export class LoopbackComponent implements OnInit{ 
    sampleString: string;

    contructor(){}

    ngOnInit(): void {}
}

Basically whatever I typed in the <input #box (keyup)="0"> will be shown immediately in the {{box.value}}. As this is purely in the html file, I am wondering how can I bind the input {{box.value}} to sampleString: string; in my component.ts so that I can use it somewhere else.

3 Answers 3

2

you can bind the method on change event in input element and update the string value

class file

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

    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent  {

       sampleString: string;

       updateBox(e) {
         this.sampleString = e.target.value; 
       }

    }

Template File

<input #box (keyup)="0" (input)="updateBox($event)">
  <p>{{box.value}}</p>
<p>This is sampleString Value: {{sampleString}} </p>
Sign up to request clarification or add additional context in comments.

Comments

1

You can use angular two way binding as shown below

@Component({
  selector: 'app-loop-back',
  template: `
    <input [(ngModel)]="sampleString">
    <p>{{sampleString}}</p>
  `
})
export class LoopbackComponent implements OnInit{ 
    sampleString: string;
   contructor(){}

    ngOnInit(): void {}
}

Comments

0

Try like this if you want to use only HTML an not 2 way binding,

<input #box (keyup)="sampleString = $event.target.value">

Working Demo

Comments

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.