Conditional HTML-Comment with Angular

Viewed 177

I have the following HTML-Code with two unordered lists (ul):

<ul class="navbar-nav mr-auto" >

   <!-- some code A here -->
   
</ul>
<ul class="navbar-nav ml-auto" >   

   <!-- some code B here -->

</ul>

Now, I want to change this under some condition to

<ul class="navbar-nav mr-auto" >

   <!-- some code A here -->
   
   <!-- some code B here -->

</ul>

Would it be possible to remove the closed ul-Tag of the first list and the opening ul-Tag of the second list with a conditional comment in angular? Can I create a label in the typescript-code which I can use in a conditional comment? Or is there another solution to solve my problem?

the "some code A & B" is a large code and I want duplicate it.

3 Answers

You can use if else structure to serve your purpose as follows.
In the below code isshowAcontent is a boolean based on your condition.

<ul class="navbar-nav mr-auto" >
<!--Conditional based by using ng-template tag-->
<ng-container *ngIf="isshowAcontent; then someContent else otherContent"></ng-container>
</ul>


<ng-template #someContent >
<div><!-- some code A here --></div>
</ng-template>

<ng-template #otherContent >
<div><!-- some code B here --></div>
</ng-template>

i think you can try this solution

<ul class="navbar-nav mr-auto" >

   <!-- some code A here -->
  <div *ngIf="condition">
   <!-- some code B here -->
  </div>
</ul>
<ul class="navbar-nav ml-auto" *ngIf="!condition" >   

   <!-- some code B here -->

</ul>

If they are large reusable blocks of code, you can make components out of them:

someCodeA.component.ts :

@Component({
  selector: 'app-some-code-a',
  templateUrl: './someCodeA.component.html',
  styleUrls: ['./someCodeA.component.scss']
})
export class SomeCodeAComponent {
...
}

someCodeA.component.html :

<li>item1</li>
<li>item2</li>
<li>item3</li>

Here you use it:

<ul class="navbar-nav mr-auto" >

   <ng-container *ngIf="showCodeA; else componentB">
       <app-some-code-a></app-some-code-a>
   </ng-container>

   <ng-template #componentB>
        <app-some-code-a></app-some-code-a>
   </ng-template>
</ul>

to create the a component, use the command: ng g c some-code-a You can also pass values to the component if your items need to hold dynamic values, check out more info at this official link: https://angular.io/api/core/Component#setting-component-inputs

Related