简体   繁体   中英

how can I simplify this app.component.html in angular 2+?

I've got a long HTML in my app.component.html that I'd like to make it appear in various conditions, again in the same HTML.

I know this has to do with ng-template and/or ng-container diectives but the articles and official docs I read and tried to understand got me confused even more... They go into too much detail that I cannot wrap my mind around or the examples thy provide does not shed light to my use-case. My use-case is much simpler than those.

Could someone show me how to simplify this sample structure below using one of those directives?

Say you have a div like this

<div id='commonHTML'>
   long html here, that you do not want to repeat in your app.component.html
</div>

And you want to display that long HTML, when a condition is true.

but I must say that this wont cut it;

<div *ngIf="myCondition == 'xyz'">
   <div id='commonHTML'>
      long html here, that you do not want to repeat in your app.component.html
   </div>
</div>

this won't cut it for me cause I want that commonHTML to show in different sections on my page... For simplicity purposes, say that I want that HTML to show at the HEADER in condition A, and at the LEFT-SIDEBAR in condition B, and in some other conditions, I want that to appear on the at the footer. So you get the idea..

My question is..

Do you wrap this in a ng-Template or an ng-Container div? Or do you throw in #templateReference in that div, and somehow, tell angular to use that reference as an insert? If so, what's the syntax?

Not the best solution, but it does take care of the dying need for the moment and put an end for me to repeat the 100 lines.

Posting it here in case it helps someone...

<ng-template #commonHTML>100 lines of HTML here</ng-template>

some html....

<div *ngIf="false;else commonHTML;">
    commonHTML will appear here. 
</div>

some more html ...

<div *ngIf="false;else commonHTML;">
    commonHTML will appear here.
<div>

The reason I call this as a not-the-best solution is because of the fact that that I need to use the "false" part.

If anyone can make this solution more handsome, please throw it in. I'll make it the accepted answer.

Divide it in different components and then include it on your main app.component.html on the basis of the condition you have ..

like if you have and then use the condition in your html to import it ..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM