Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 8: Passing html as input variable

We can use @Input as passing input props or data. We also can use <ng-content> to dump a load of html into the children component. Is there any way to pass html as Input. Like @Input html1, @Input html2, and use them in the child class component?

Suppose I have this html in child class:

<div class='wrapper'>
  <div class="content1 exclusive-css-defined-to-this-component">
     <div>{$content1}</div>
  </div>
  <div class="content2 exclusive-css-defined-to-this-component-2">
    <div>{$content2}</div>
  </div>
</div>

And I want to pass $content1 & $content2 as input.

like image 840
Sakibur Rahman Avatar asked Nov 05 '19 23:11

Sakibur Rahman


2 Answers

I have found the solution, this can be done by:

<div class='wrapper'>
  <div class="exclusive-css-defined-to-this-component">
     <div><ng-content select="[content1]"></ng-content></div>
  </div>
  <div class="exclusive-css-defined-to-this-component-2">
    <div><ng-content select="[content2]"></ng-content></div>
  </div>
</div>

And we can use the component like:

<wrapper>
   <div content>Any thing you want to put in content1</div>
   <div content2>Any thing you want to put in content2</div>
</wrapper>
like image 91
Sakibur Rahman Avatar answered Sep 18 '22 09:09

Sakibur Rahman


We can use innerHTML to achieve this

Sample example demonstrating this,

parent.component.ts,

export class ParentComponent {
  htmlOneAsString = `
    <div>Welcome Text Header</div>
  `;

  htmlTwoAsString = `
    <div>Welcome Text Content</div>
  `;

  htmlAsString = `
    <div><div>${this.htmlOneAsString}</div><div>${this.htmlTwoAsString}</div></div>
  `;
}

parent.component.html,

<child [innerHTML]="htmlAsString"></child>

child.component.ts,

@Component({
  selector: 'child'
})
export class ChildComponent {
  @Input() htmlAsString: string;
}

child.component.html,

<div>{{htmlAsString}}</div>
like image 21
Gangadhar Gandi Avatar answered Sep 22 '22 09:09

Gangadhar Gandi