简体   繁体   中英

Use local variable in template html without component Angular2+

I want to use a local variable into my html template to use it in css classes but without linking it with the component. I want to do that :

[local_html_variable = 1]

    <div class="css-{{ local_html_variable }}">
            Div #1
        </div>

[local_html_variable + 1]

        <div class="css-{{ local_html_variable }}">
            Div #2
        </div>

[local_html_variable + 1]

        <div class="css-{{ local_html_variable }}">
            Div #3
        </div>

        ...

to get

<div class="css-1">
        Div #1
    </div>

    <div class="css-2">
        Div #2
    </div>

    <div class="css-3">
        Div #3
    </div>

    ...

Important : the number of div is dynamic. But I don't achieve it. I tried with <ng-template let-localHtmlVariable> but didn't work.. Any idea ?

You can use *ngFor structural directive

<div *ngFor="let value of [1,2,3]" class="css-{{value}}">
   DIV #{{value}}
</div>

Here is a very situational answer that takes advantages of truhy/falsy values :

<ng-container *ngIf="1 as i">
  Number is {{ i }}
</ng-container>

Use it in your classes in the container itself :

<div class="css-{{ i }}">With interpolation</div>
<div [class]="'css-' +  i">With input</div>

Here is the stackblitz : https://stackblitz.com/edit/angular-3wm4en?file=src%2Fapp%2Fapp.component.html

EDIT explanation :

In javascript, every value can be transalted to boolean : they are truthy or falsy values.

The quick boolean parse operator is the !! double negation.

Let's try :

 console.log(!!''); console.log(!!0); console.log(!!5); 

When we use this notation, the evaluation use the same principle : it tests if the given value is truthy or falsy. In numbers, 1 being truthy, the test checks out, and the as i notation simply creates a template variable.

For information, falsy values are 0, '', null, undefined, infinity, NaN .

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