0

so What I want is, on button click add item.name to a new array :

<button (click)="addDistrict(item.name)" *ngFor="let item of items" ion-button>{{item.name}}</button>

myDist = [];

addDistrict(item.name){
   this.myDist.push(item.name)
  }

How to do that properly ?

7
  • addDistrict(item.name) <--- throws syntax errors Commented Oct 5, 2018 at 10:03
  • because in ts file item.name is unknown Commented Oct 5, 2018 at 10:05
  • 1
    use addDistrict(item) and this.myDist.push(item) Commented Oct 5, 2018 at 10:05
  • Are you sure your object has the property "name" in it? Commented Oct 5, 2018 at 10:05
  • You should also post your .html template and typescript file (not entirely but your interfaces and the click event handler would be helpful) Commented Oct 5, 2018 at 10:06

2 Answers 2

1

An answer posted by @tftd is correct and which solve your problem too. But I would write something like this:

In HTML:

// Will pass the object in to the method like

<button (click)="addDistrict(item)" *ngFor="let item of items" ion-button> 
   {{item.name}}
</button>

and in TS file:

addDistrict(item){
   // will extract the related key from Object here to push it in array
   this.myDist.push(item.name);
}

StackBlitz Example

Sign up to request clarification or add additional context in comments.

Comments

1

Your addDistrict function's argument is incorrect as well as the varialbe you are passing to it from the template.

In the template you are passing item.name which is a string and then in the function you have item.name again (which yould fail because you can't have a variable name containing a dot). This should work

addDistrict(name){
    this.myDist.push(name)
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.