We want to show source code example into a sample gallery.
We have typescript , html and HTML files we want to show as it is done into the angular.io component samples pages.
Do you know how to get the source code from the path of a typescript file already in our project and render it ?
for the angular.io they use this component https://github.com/angular/angular/blob/main/aio/src/app/custom-elements/code/code-example.component.ts but with complex build and rendering, too complex... Eric
The code samples are usually not code from your own codebase.
They're rather examples of what to write to use a library (or something) you've created.
So it's kind of a no-brainer : don't create .ts file and load them as text, but rather :
Or, if you want to have autocomplete on the TS content
assets folder so that it does not get built, and load it through the HttpClient[...] how to get the source code from the path of a typescript file already in our project and render it ?
You can use the Fetch API which will asynchronously retrieve a file from your server.
N.B. Using the Fetch API starts with two asynchronous operations:
Example:
const getMyTSFile = async () => {
// FETCH THE FILE RESPONSE
const myTSFile = await fetch('/path/to/my/typescript-file.ts');
// EXTRACT THE CONTENT FROM THE FILE (AS TEXT)
const myTSFileText = await myTSFile.text();
// CREATE A NEW <CODE> ELEMENT
const myTSFileElement = document.createElement('code');
// POPULATE THE THE <CODE> ELEMENT WITH THE FILE TEXT CONTENT
myTSFileElement.textContent = myTSFileText;
// APPEND THE <CODE> ELEMENT TO THE DOCUMENT BODY
document.body.append(myTSFileElement);
}
getMyTSFile();
Further Reading:
Initially I posted a question here :
How to replace raw-loader when migrating to Angular 12?
We include actually source code from the codebase with an Angular 11 application like this :
html: require(!!raw-loader!./${files}.component.html)
or
ts: require(!!raw-loader!./${files}.component)
but raw-loader disappears when we migrate to Angular 12. And I tried with ?raw that works for html file :
html: require(./${files}.component.html?raw)
and not for typescript file :
ts: require(./${files}.component?raw)
the !! that prevents loaders is not working.
any ideas ?