1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

Angular get access of dynamic elements and change the values

Discussão em 'Angular' iniciado por Reegan, Setembro 16, 2025.

  1. Reegan

    Reegan Guest

    I have Angular component that contains number of products which are dynamically created using ngFor directive. Here I need to access each products quantity and control using increament and decreament buttons. But this was somewhat critical to do. Can someone suggest the good optimize approach to handle this. html

    <div class="productcontainer">
    <ng-container *ngFor="let product of productlists; let i=index">
    <div class="products" *ngIf="product.productPrice > 0">
    <h4>{{product.productName}}</h4>
    <p>Rs. {{product.productPrice}}</p>
    <button mat-icon-button (click)="decrement(i)" color="accent" #buttondecreament>
    <mat-icon>remove</mat-icon>
    </button>
    <mat-form-field style="width: 50px;">
    <input matInput [(ngModel)]="quantity" size="2" [id]="'quantity_input'+i" #quantityreference="ngModel">
    </mat-form-field>
    <button mat-icon-button (click)="increment(i)" color="accent" #buttonincreament>
    <mat-icon>add</mat-icon>
    </button>
    </div>
    </ng-container>
    </div>

    ts file


    export class ProductsComponent implements OnInit {
    @ViewChildren('quantityreference') dynamicElements!: QueryList<ElementRef>;
    productlists = JSON.parse(`[
    {
    "productId": "T000",
    "productName": "Punnakuuu",
    "productQuantity": "2",
    "productPrice": "40",
    "gst":"20"
    },
    {
    "productId": "T1111",
    "productName": "Thenkaai Punnaku",
    "productQuantity": "2",
    "productPrice": "40",
    "gst":"18"
    },
    {
    "productId": "MT1",
    "productName": "Mattu Theevanam",
    "productQuantity": "2",
    "productPrice": "55",
    "gst":"18"
    },
    {
    "productId": "CP1",
    "productName": "m Punnaku",
    "productQuantity": "10",
    "productPrice": "55",
    "gst":"12"
    },
    {
    "productId": "CP2",
    "productName": "ell Punnaku",
    "productQuantity": "10",
    "productPrice": "22",
    "gst":"12"
    }]`
    );

    ngtemplatetest: boolean = true;
    quantity: number = 0;
    constructor() { }

    ngOnInit(): void {
    this.ngtemplatetest = true;
    }
    increment(indexvalue: number) {
    this.quantity++;
    let cc = document.getElementById('quantity_input' + indexvalue.toString())
    console.log("the index value is" + cc?.nodeValue);

    }
    decrement(indexvalue: number) {
    if (this.quantity > 0) {
    this.quantity--;
    }
    }
    }


    [​IMG]

    Currently when I change the quanity it is reflecting in all products. Can someone provide solution

    Continue reading...

Compartilhe esta Página