Search code examples
angularangular2-directives

How to bind the component selector to display dynamic string data in Angular 4


I am using angular 4 in my application and I wanted to use a reusable component which helps me to display some information dynamically based on the user. So as a first step I have created component!.

import { Component, OnInit, Input } from '@angular/core';
import {Router} from '@angular/router';

@Component({
  selector: 'pageInfo',
  templateUrl: './pageInfo.component.html',
  styleUrls: ['./pageInfo.component.scss']
})
export class PageInfoComponent implements OnInit {


  public info: string;
  public manipulatedString: string;

  constructor() {
  }

  ngOnInit() {
  }

  stringManipulation(){

    this.manipulatedString = "" // Some sort of manipulation using this.info string value

  }
}

Now I will start using <pageInfo></pageInfo> tag in some other html pages, while using I want to pass some hard coded string value into PageInfoComponent class through Component selector. After getting string value PageInfoComponent class will manipulate it and add some sort of styles and the result will be displayed.

pageInfo.component.html

<div>{{manipulatedString}}</div>

So how can I pass string value from component selector to it's class, so that I can display manipulated string with reusable component.


Solution

  • You can add

    <ng-content></ng-content>
    

    to the template of your pageInfo component

    or you can pass the string to an input of your pageInfo component

    @Input() manipulatedString:string;
    

    and the component displays the string itself

    <span [innerHTML]="manipulatedString"></span>
    

    For this you need to use the DomSanitizer to indicate to Angular that it's safe to add HTML tags from this string (your responsibility that it doesn't contain harmful HTML) and use it like

    <pageInfo [content]="manipulatedString"></pageInfo>
    

    You would need to add <div></div> in TypeScript, or

    <pageInfo [content]="'<div>'+manipulatedString+'</div>'"></pageInfo>