DBoi
DBoi

Reputation: 687

Angular inject html template as string

I'm looking to send an email as a string to an API via a service using Angular 6.

I would like to have a separate HTML file that has the code for this email template. I would then like to pass in this HTML template to the service and then post it to the API. (Please note - I do not want to build the email template as a string. i want to build it in HTML and then convert it to string).

So say i have the following files:

  1. email-template.html - holds the html email template code

  2. email.service.ts - posts the email template code as string

How would I implement this?

Here is my service:

constructor(private httpClient: HttpClient) { }

  send(recipient, email) { <=== need that 'email' perameter to be the email template.html as string

    const object: Email = {
      FromAddress: environment.noreplyEmailAddress,
      ToAddress: recipient,
      MessageBodyText: null,
      MessageBodyHtml: email.template,
      Subject: email.subject
    };

    return this.httpClient.post(`${this.url}/api/storeemail`, object, httpOptions);
  }

Upvotes: 3

Views: 2590

Answers (1)

Bunyamin Coskuner
Bunyamin Coskuner

Reputation: 8859

You can simply import it within your component. Here is a working solution When you click on Click me button, it logs a html content into the console.

This is how you do it. First create a template in a file called email-template.html and put it somewhere (I put it in the same folder) and load it as follows.

import returns a Promise. You can do whatever you want within then

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';

  send() {
    import('./email-template.html').then(res => {
      console.log(res.default);
    });
  }
}

Upvotes: 1

Related Questions