Set and get attributes from HTML templates

Last Updated on

Set an attribute by using square brackets, name of attribute, and its value:

<ng-container *ngIf="arrIngredients">
    <div id="ingsBox">  
        <div class="ing"
        id="{{'ing'+ing.id}}"
        [attr.name]="ing.name"
        (click)="toggleClick($event)"
        *ngFor="let ing of arrIngredients;">
            {{ing.name}} <br>
            <!-- {{ing.description}} -->
            <hr>
        </div>
    </div>
</ng-container>

Get it in the components via the getAttribute method, i.e.:

  toggleClick(event) { //example function
    alert(event.target.id);
    alert(event.target.getAttribute("name")); //getting it here.
  }

Lämna ett svar