0

I basically have a button that once pressed will output whatever has been typed into the user input.

However my function that assigns the user input to a variable isn't being recognised for some odd reason?

app.component.html:

<div style="text-align:center">
<h1>Word Hider</h1>
 <p></p>
   <input type="text" class="wordHide" value="Insert Text">
 <p></p>
   <button  id='userIn' (click)='takeUserStr()'>Submit!</button>
<p></p>
   <button>Hide Word!</button>
<div>
  Your Word Is: {{ userWord }}
</div>
</div>

app.module.ts:

   import { BrowserModule } from '@angular/platform-browser';
import { NgModule, OnInit } from '@angular/core';


import { AppComponent } from './app.component';


  @NgModule({
     declarations: [
     AppComponent,
   ],
 imports: [
  BrowserModule
  ],
 providers: [],
 bootstrap: [AppComponent]
  })
export class AppModule {
userWord = 'this is a test';
  ********************function***********************
  takeUserStr(event: any) {
    this.userWord = (<HTMLInputElement>event.target).value;
  }

}

2 Answers2

0

You need to have the function declared in app.component.ts , also it should not take any parameter as you defined in HTML

takeUserStr() {
    this.userWord = (<HTMLInputElement>event.target).value;
}
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
0

Component are isolated in nature, they only understand whats present inside their context(this), whatever you kept in the own class. In addition to that it also recognises Input + Output bindings + Injectors

You have kept your function in AppModule, which isn't reachable on your component template. You should move out that function to your app.component.ts

Basically everything that is bounded to your component html, that you have to move inside app.component.ts

@Component({...})
export class AppComponent {
  userWord = 'this is a test';

  takeUserStr(event: any) {
     this.userWord = (<HTMLInputElement>event.target).value;
  }
}

Also pass $event object as in parameter of takeUserStr function.

(click)='takeUserStr($event)'

Though my recommendation to implement this scenario using @angular/forms, either model driven or template driven forms.

Check Use ngModel with Angular

Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299