Home > other >  Angular how to wrap input value with double curly braces
Angular how to wrap input value with double curly braces

Time:03-16

What I want to achieve is that when I write inside input field "Foo" it will become {{Foo}}

CodePudding user response:

First create this directive :

import { Directive, ElementRef, Renderer2, DoCheck } from '@angular/core';
import { distinctUntilChanged, debounceTime, tap } from 'rxjs/operators';
import { fromEvent } from 'rxjs';

@Directive({
  selector: '[format-input]',
})

export class FormatDirective implements DoCheck {

  valueIsNull:boolean = true;

  constructor(public _elementRef: ElementRef<HTMLInputElement>,
    private _renderer: Renderer2) { }

  ngDoCheck(): void {

    setTimeout(() => {
      if(this.valueIsNull){
        this.format();
      }
    }, 150)

    fromEvent(this._elementRef.nativeElement, 'click')
      .pipe(
        debounceTime(100),
        distinctUntilChanged(),
        tap(() => {
          this.format();
        })
      )
      .subscribe();
  }

  format(){
    this._elementRef.nativeElement.value = "{{ "   this._elementRef.nativeElement.value   " }}"
    this.valueIsNull = false;
  }
}

Then Import it to your module : e.g app.module :

@NgModule({
  declarations: [
    FormatDirective
  ],
  imports: [CommonModule],
  exports: [
    FormatDirective
  ]
})
export class AppModule { }

Then you can use it anywhere you want :

<input type="text" format-input />

CodePudding user response:

You should use angular templating to achieve this Official Documentation for templating and interpolation and a code sample is given below. this will help you to achieve your usecase.

https://angular.io/guide/interpolation https://angular.io/api/forms/NgModel

import {Component} from '@angular/core';
import {NgForm} from '@angular/forms';

@Component({
  selector: 'example-app',
  template: `
    <form #f="ngForm" (ngSubmit)="onSubmit(f)" novalidate>
      <input name="first" ngModel required #first="ngModel">
      <input name="last" ngModel>
      <button>Submit</button>
    </form>

    <p>First name value: {{ first.value }}</p>
    <p>First name valid: {{ first.valid }}</p>
    <p>Form value: {{ f.value | json }}</p>
    <p>Form valid: {{ f.valid }}</p>
  `,
})
export class SimpleFormComp {
  onSubmit(f: NgForm) {
    console.log(f.value);  // { first: '', last: '' }
    console.log(f.valid);  // false
  }
}

Thanks

Rigin Oommen

  • Related