Home > Software engineering >  how to add input fields on the location of some words in a string
how to add input fields on the location of some words in a string

Time:01-17

I have a string which contains some words under large brackets (like-[name],[father_name]). I want to replace these words with input fields to enter actual value. suppose I have a string...

Dear Mr. [Father_name], your son/daughter [name] not attend class today.

the string I want...

Dear Mr. Shankar, your son/daughter Prashant not attend class today.

component.ts

message:string = '';
convertString() {
  let message = Dear Mr. [Father_name], your son/daughter [name] not attend class today.
  let matches = message.match(/\[(.*?)\]/g);
  for(let match of matches) {
     message = message.replace(match, `<input type="" />`);
  }
this.message = message;
}

component.html

Dear Mr. <input type="" />, your son/daughter <input type="" /> not attend class today.

input are print as a string instead of render. I want to show input fields on locations of matched words and how to convert input field value in a string again.

CodePudding user response:

The "quick" answer is "use DomSanitizer" to pass to a innetHTML

constructor(private sanitizer:DomSanitizer){}
convertString() {
  let message = Dear Mr. [Father_name], your son/daughter [name] not attend class today.
  let matches = message.match(/\[(.*?)\]/g);
  for(let match of matches) {
     message = message.replace(match, `<input type="" />`);
  }
 this.messageHTML = sanitizer.bypassSecurityTrustHtml(message);
}

and use

<div [innerHTML]="messageHTML"></div>

But you're entering in problems when you want to recover the result because you need use javascript to get the value, so...

...we are going to "think in Angular"

Imagine you have an array of object with two properties, "index" and "text". Some like:

data=[{
    "index": -1,
    "text": "Dear Mr. "
  },
  {
    "index": 0,
    "text": "[Father_name]"
  },
  {
    "index": -1,
    "text": ", your son/daughter "
  },
  {
    "index": 1,
    "text": "[name]"
  },
  {
    "index": -1,
    "text": " not attend class today."
  }
]

We can declare a variable

values:string[]=[]

And have an .html like

<ng-container *ngFor="let dat of data">
  <span *ngIf="dat.index==-1">{{dat.text}}</span>
  <input *ngIf="dat.index!=-1" [(ngModel)]="values[dat.index]">
</ng-container>

To get the text we can use a getter

  get texto(){
    let text="";
    let index=0;
    this.data.forEach(x=>{
      text =x.index==-1?x.text:(this.values[index  ] ||"")
    })
    return text
  }

So, the only is create the array of objects

  ngOnInit()
  {
    const part=this.text.split(/(\[.*?\])/);
    let index=0;
    this.data=part.map(x=>({
       index:x.match(/(\[.*?\])/)?index  :-1,
       text:x
    }))
  }

and put in a stackblitz

  • Related