0

I'm working on the front-end side of a web application and would like to receive JSON object data when I click on the drop down values on my HTML page.

Someone please explain to me how this can be done.

4
  • 2
    Can you provide some code? Have you already tried something ? Commented Feb 2, 2018 at 20:49
  • do you want to have a json object in the ngModel? you can use ngValue for that. Commented Feb 2, 2018 at 20:53
  • Possible duplicate of Angular 2 - fetch data from local json to populate dropdown Commented Feb 2, 2018 at 21:30
  • To be clear, there's no such thing as a "json object" There's an object, and there's a string in JSON format. Commented Feb 3, 2018 at 0:59

1 Answer 1

0

If you wish to have an object json saved as a select element's model value you can use it by using ngValue on the option elements.

<select [(ngModel)]="selected">
         <option *ngFor="let value of values" [ngValue]="value">{{value.name}}</option>
      </select>|

You can see a working example here.

If you want to do something with the value when a value is selected you can listen on the ngModelChange event.

<select [(ngModel)]="selected" (ngModelChange)="handleChange($event)">
         <option *ngFor="let value of values" [ngValue]="value">{{value.name}}</option>
      </select>|

And define the method to call in your controller.

export class App {
  name:string;
  selected = null;
  values = [{name:'a'}, {name:'b'}, {name:'c'}]
  history = [];
  constructor() {
    this.name = `Angular! v${VERSION.full}`
  }

  handleChange(value) {
    this.history.push(value);
  }
}

A working example can be found here.

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

3 Comments

I have the HTML code, but need a basic component.ts code and a code for the service.ts class.
check the examples, I'll add the controller in here too.
This is perfect! Thank you so much! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.