Kasunt
Kasunt

Reputation: 55

Angular access html content via .ts file

I want to get access input field [newUser] value in button click action [onAddUser()] in .ts file.

<input type="text" 
        ng-model="newUser"
        style="text-align:center"/>
<button (click)="onAddUser()" >Add User</button>

Upvotes: 1

Views: 2721

Answers (1)

gagan
gagan

Reputation: 269

If you are using Angular (not AngularJS 1.x) then you need to change the NgModel syntax:

In HTML (template):

<input type="text" 
         [(ngModel)]="newUser"
         style="text-align:center"/>
<button (click)="onAddUser()" >Add User</button>

In TS file:

export class YourComponent {
  newUser: string;

  onAddUser(){
    alert(this.newUser); //get the input value
  }
}

Also, remember to import the FormsModule:

import { FormsModule, ReactiveFormsModule } from '@angular/forms';

@NgModule({
  bootstrap: [AppComponent],
  declarations: [AppComponent],
  imports: [
    CoreModule,
    FormsModule
  ],
})
export class AppModule {}

Upvotes: 3

Related Questions