How to get form input, select value using Angular Binding?

I am new to angular2. So please carry me. I know this is a question for someone.

<form> <label class="input-group"> <p>View By</p> <select [(ngModel)]="balance.viewBy" name="viewBy"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select> </label> <label class="input-group"> <p>Date From</p> <input [(ngModel)]="balance.dateFrom" name="dateFrom"/> </label> <label class="input-group"> <p>Date To</p> <input [(ngModel)]="balance.dateTo" name="dateTo"/> </label> <button type="button" (click)="search_data_balance()">Search</button> </form> 

component.ts

 export class BalanceComponent { search_data_balance(){ // get all input value. } } 

What I tried so far

 let vb = balance.viewBy, df = balance.dateFrom, dt = balance.dateTo; // returns error 

In corner1, we can get the value of those that use $ scope.

Any help would be greatly appreciated. Thanks.

+7
javascript angular typescript
source share
3 answers

If you can change the markup. I deleted the balance. I do not know how to use balance in angular2.

 <select [(ngModel)]="viewBy" name="viewBy"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select> <button type="button" (click)="search_data_balance(viewBy)">Search</button> 

In your component. You must define each model in the class.

 export class BalanceComponent { viewBy: any; // define viewBy = 1; // set value search_data_balance(view){ console.log(view); } } 

Edit 2:

// pass the balance object to the arguments of the function. That way you can get it from the class component

 <button type="button" (click)="search_data_balance(balance)">Search</button> 

component

 export class BalanceComponent { // defining balance in component // 1 is the default value. You can set it whatever you want. private balance = { viewBy: 1 }; search_data_balance(balance){ console.log(balance); console.log(balance.viewBy); // viewBy value } } 

Hope it works for you. Hooray!

+1
source share

balance.viewBy will contain the value after changing the selection.

Value (for strings) or ngValue (for other types) must be set

  <option [ngValue]="1">1</option> <option [ngValue]="2">2</option> <option [ngValue]="3">3</option> <option [ngValue]="4">4</option> <option [ngValue]="5">5</option> 
+2
source share

So, you are trying to connect the various properties of the model object (ordinary object) with various controls.

A model object must exist in your component as a property. You must initialize your model as part of your component. Then, in order to get the values, you should look for properties as such in this object:

 export class BalanceComponent { private balance = {}; // <---- search_data_balance(){ console.log(this.balance.dateTo); // <---- } } 
+2
source share

All Articles