简体   繁体   中英

I am able to reverse a string using JavaScript function but how to do it using a form input and button click in Angular?

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'));
  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.
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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM