user111111 user111111 - 1 month ago 8
TypeScript Question

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

I am new in angular2. So, please bear with me. I know this is a noob question for some.

<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 have tried so far

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

// returns error


In angular1, we can get the value of those using $scope.

Any help would be appreciated. Thanks.

Answer

If you can change your markup. I removed balance. I don't know how can I used 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 should define each model into class.

export class BalanceComponent {
    viewBy: any;   // define
    viewBy = 1;    // set value

    search_data_balance(view){
        console.log(view);    
    }
}

Edit 2:

// pass balance object in function arguments. So, you can get it from 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 with you. Cheers!

Comments