Home > Enterprise >  How To Get Value Of Input Tag In Angular?
How To Get Value Of Input Tag In Angular?

Time:07-21

How To Get Value Of Input tag in typescript.

<input type="checkbox" id="demo111" (click)="chk(this)" name="schoolFactors" value="Yes" >Yes

I'm using the below code but not sure how to get & set the input box value using typescript in angular.

chk(this){
   console.log(this);
 }

CodePudding user response:

If you dont want to use two way data binding. You can do this.

In HTML

<form (ngSubmit)="onSubmit($event)">
   <input name="player" value="Name">
</form>

In component

onSubmit(event: any) {
   return event.target.player.value;
}

CodePudding user response:

Depends on the circumstances, another way that does not have to involve a <form> is by using ViewChild and elementRef. A very simplistic example:

HTML:

<input #cb type="checkbox" id="demo111" (change)="chk(cb.value)" name="schoolFactors" value="Yes" >Yes

Class code:

Demonstrates getting (via parameter from the HTML and directly in code) and setting the value:

  @ViewChild('cb') cb: ElementRef;

  chk(e): void {
    const nativeCb = this.cb.nativeElement as HTMLInputElement;

    console.log(e, nativeCb.value);
    nativeCb.value = 'no';
  }
  • Related