Home > Net >  I am able to reverse a string using JavaScript function but how to do it using a form input and butt
I am able to reverse a string using JavaScript function but how to do it using a form input and butt

Time:10-02

you may see that I am able to execute reverse of a word and print in console but how to implement it using input and a button click in Angular. Thanks.

Here is the stackBlitz link

Sample code:

function reverseLetters(str){
  let stack = [];
  for(let i=0; i<str.length; i  ){
    stack.push(str[i]);
  }

  let reverseStr ='';
  while( stack.length > 0){
    reverseStr  = stack.pop();
  }
  return reverseStr;
}

console.log(reverseLetters('Angular'));

CodePudding user response:

  1. Add two-way binding to your form control with [(ngModel)]="yourstringvar.
  2. add (click) event to your button like <button (click)="onButtonClick()">lol</button>
  3. Create the onButtonClick() method and put your javascript code inside.

CodePudding user response:

Add button and input field as

<input type="text" [(ngModel)]="inputText" />

<button (click)="handleReverse()">Reverse</button>

{{ reversedInput }}

In tS, reversedInput will contain your reversed string

  inputText = null;
  reversedInput = null;

  handleReverse() {
    this.reversedInput = this.reverseLetters(this.inputText);
  }

  reverseLetters(str) {
    let stack = [];
    for (let i = 0; i < str.length; i  ) {
      stack.push(str[i]);
    }

    // stack = [...str]; shorthand to skip above for loop

    let reverseStr = '';
    while (stack.length > 0) {
      reverseStr  = stack.pop();
    }
    return reverseStr;
  }

Angular Demo

CodePudding user response:

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

import {AppRoutingModule} from './app-routing.module';
import {AppComponent} from './app.component';

import {FormsModule} from "@angular/forms";

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {
}
import {Component} from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'ng-inbox';
  _string: any;
  reversedString: any = '';

  reverseString() {
    let strStack: string[] = [];
    let _reverseStr: string = '';
    this._string
      .split('')
      .map((letter: string) => {
        strStack.push(letter);
      })
      .map((letter: string) => {
        this.reversedString  = strStack.pop();
      });

  }
}
<input type="text" [(ngModel)]="_string">
<button (click)="reverseString()">Reverse Str</button>
<p>{{reversedString}}</p>

I hope the above code will help you

  • Related