Asif Zaidi
Asif Zaidi

Reputation: 93

How to read HTML file into component in Angular

I am trying to create dynamic print template in Angular 12. I would like to fill the html body text dynamically based on the parameter passed on the selector used in the main component view. Print layout component is in Shared module and both the html templates are in app folder.

My requirements are:

  1. I want to read the html file in the print layout component and display it. I don't want to create component and render the component in the print layout

  2. I don't want to save the html file in the backend and trigger api to fetch the html

print-layout.component.html

<div [innerHtml]="myTemplate"></div>

print-layout.component.ts

@Component({
            selector: 'app-print-layout',
            templateUrl: './print-layout.component.html',
            styleUrls: ['./print-layout.component.scss']
        })            
        
        export class PrintLayoutComponent implements OnInit{
            @Input() modalID;
            myTemplate;    

            ngOnInit() {
                   if(modalID == "1")
                      template = '../../app/tools/test/test-message1.html';
                    else (modalID == "2")
                        template = '../../app/tools/test/test-message2.html';
            }
           
        }

Also, I have gone through this solution Read HTML File into template in Angular 2? where they are creating component dynamically from main component file.

Is there any way to display html template file in the main component without creating component. Also, please suggest is it the right way to display html content without creating component in Angular...?

Upvotes: 1

Views: 1325

Answers (1)

apnnux
apnnux

Reputation: 420

You can try to use iframe tag inside the print-layout.component.html like this

<iframe [src]="myTemplate"></iframe>

Obviously on ngOnInit() you need to assign path to myTemplate as same name to use in html

Upvotes: 0

Related Questions