how do i render placeholder template attributes on a page?

A simple solution is to make use of pipes.

So for example you have an object like

export class Candidate{
    public id: number;
    public name: string;
}

And you want to store the keys in database or in json file or whatever (the key is that they will be rendered dynamically), to illustrate lets say my key is stored in a variable in component like this

public key: string = "{{candidate.name}}";

Now I’ve created a pipe that will check the key and return the corresponding object property, like this.

export class TransformkeyPipe implements PipeTransform {
  transform(value: any, args: any): any {
if (value == "{{candidate.name}}") {
  return args.name;
}
if (value == "{{candidate.id}}") {
  return args.id;
}
return null;
  }
}

In the component file, I’ll apply the pipe along with the actual object that has the data. Something like this

<p>{{key | transformkey: candidate}}</p>

EDIT:

In case you want to replace placeholders in a string, then simply you’ll have to use javascript match function to extract out the placeholders using some regex. And then one by one replace them with actual data. Something like this.

export class Transformkey2Pipe implements PipeTransform {
  transform(value: string, args: any): any {
const regexp = /{{[a-z]*.[a-z]*}}/g;
const array: string[] = value.match(regexp);

array.forEach(x => {
  switch (x) {
    case "{{candidate.name}}":
      value = value.replace(x, args.name);
      break;
    case "{{candidate.id}}":
      value = value.replace(x, args.id);
      break;
  }
});

return value;
}
}

EDIT 2 In case you want to use multiple data-sources, one approach could be to pass the objectType parameter to your pipe, and based on that decide which field of datasource to picke. Something like this

export class Transformkey3Pipe implements PipeTransform {
  transform(value: string, args: any, objectType: string): any {
const regexp = /{{[a-z]*.[a-z]*}}/g;
const array: string[] = value.match(regexp);

array.forEach(x => {
  switch (x) {
    case "{{key.name}}":
      if (objectType == "candidate") {
        value = value.replace(x, args.name);
      }
      if (objectType == "employee") {
        value = value.replace(x, args.emp_name);
      }
      break;
    case "{{key.id}}":
      if (objectType == "candidate") {
        value = value.replace(x, args.id);
      }
      if (objectType == "employee") {
        value = value.replace(x, args.emp_id);
      }
      break;
  }
});

return value;
  }
}

Please find the updated stackblitz.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top