HVenom
HVenom

Reputation: 762

passing attribute of element to a function in angular 4/5

I want to pass attribute values of elements to a function at a button click and here's how i am doing it

<div>
  <ul #list>
    <li class="radio" *ngFor="let option of options; let j = index" id={{i}}-{{j}} #item>
      <label><input type="radio" #opt  name={{i}} value={{option}} /> {{option}} </label>
    </li>
  </ul>
</div>
<button type="button" (click)='func(opt.value, item.id, list)'>submit</button>
   

what i am doing here is

  1. I am passing the value of radio button(first arg)
  2. passing the id of the list item(second arg)
  3. passing the reference of the entire list (third arg)

But of course it's not working the error message says cannot read value of undefined(first arg) and I suspect the same will happen for the rest of the argument as well.

So my question is how do i pass the attribute value to the function?

PS: I am new to angular stuff

Upvotes: 2

Views: 2531

Answers (1)

Joseph Webber
Joseph Webber

Reputation: 2173

You could set variables to the selected option's value and item ID on change() and pass those in when you click the button.

<div>
  <ul #list>
    <li class="radio" *ngFor="let option of options; let j = index" id={{i}}-{{j}} #item>
      <label><input type="radio" #opt name={{i}} value={{option}} (change)="selectedOptionValue=option.value; selectedItemID=item.id" /> {{option}} </label>
    </li>
  </ul>
</div>
<button type="button" (click)='func(selectedOptionValue, selectedItemID, list)'>submit</button>

Just be sure to check those values in your backend func function to see if they're set.

Upvotes: 2

Related Questions