How to add conditional attribute in Angular?

2019-09-19 11:53发布

问题:

In my Angular project (v6) have a table as shown below and I list the records by checking index numbers of them. I want to display all the records on the first page (5 records) and animate using Angular-Animations only the first record. The following example displays all records with animation (but I just want to animate the first row).

<ng-template pTemplate="body" let-row let-i="rowIndex">
    <tr *ngIf="i==0" [@fadeInOnEnter]>
        <td>
            <a [routerLink]="['/detail/']">{{ row.Title }}</a>
        </td>
        <!-- other stuffs -->
        <td>
            <!-- ... -->
        </td>
    </tr>
</ng-template>

On the other hand, when I use *ngIf - else I have to use the same <tr/> block twice that I do not want. I also tried to use [@fadeInOnEnter]="i==0" and [attr.@fadeInOnEnter]="i === 0 ? '' : null" but for each of them, one record with animations or all records without animations are listed. Is there any way to fix this problem?


Update I : I had already tried to use it, but in that case my code returns as on the following. Is there any mistake for my usage on Update I?

<ng-template pTemplate="body" let-row let-i="rowIndex"> 
    <ng-container *ngIf="i==0; then fadeBlock else elseBlock">

        <ng-container #fadeBlock>
            <tr [@fadeInOnEnter]> <!-- tr WITH animation -->
                <td>...</td>
                <td>...</td>
                <td>...</td>
                <td>...</td>
                <td>...</td>
            </tr>
        </ng-container>

        <ng-container #elseBlock>
            <tr>  <!-- tr WITHOUT animation -->
                <td>...</td>
                <td>...</td>
                <td>...</td>
                <td>...</td>
                <td>...</td>
            </tr>
        </ng-container>

    </ng-container>            
</ng-template>

回答1:

You could use a ternary condition.

<tr [@fadeInOnEnter]="condition ? '' : null"></tr>

With this, if the condition is an empty string ('') it'll be applied.



回答2:

I don't know much about Angular Animation 6, in Angular 8 animation you can use some like

animations: [

    trigger('simpleFade', [
      transition('*=>0', [
        style({ transform: 'translateX(+100%)' }),
        animate(350)
      ])])]

And

<table>
  <tr *ngFor="let data of list;let i=index" [@simpleFade]="i">
    <td >{{data}}</td>
  <tr>
</table>

Yes, you create the animation from any state to 0 *=>0 not use :enter. NOTE: Sorry about my original idea using <ng-container> a ng-container don't create tag, so we can not add any attribute to a ng-container

See a simple animation in stackblitz