I am re-asking the question because I left out vital info previously.
I have a date model which changes the values of an input based on this: AngularJS: How to set default value to ng-model="searchText"?.
<div class="modal-body">
<div style="display:inline-block; margin-bottom:20px;">
<h3 style="float:left;">Set All Dates: </h3>
<span style="padding-top:15px; padding-left:7px;" class="input-group date">
<input id="setAllEffectiveDates" type="text" data-ng-model="date" value="" class="form-control input-sm">
<span class="input-group-addon"><i class="glyphicon glyphicon-th"></i></span>
</span>
</div>
<table class="table table-bordered">
<tbody data-ng-repeat="(associatedContract,ndc) in ndcs">
<tr>
<td>
<div class="input-group date updateIt">
<input id="effectiveDate" type="text" data-ng-model="date" class="form-control input-sm">
<span class="input-group-addon"><i class="glyphicon glyphicon-th"></i></span>
</div>
</td>
</tr>
</tbody>
</table>
</div>
The above works as intended, when I select a date all of the inputs change to that selected date.
My problem is that I want to add a default value to the fields. This value is a variable that is being iterated through here: <tbody data-ng-repeat="(associatedContract,ndc) in ndcs">.
<input id="effectiveDate" type="text" data-ng-model="date" ng-init="date=ndc.value" class="form-control input-sm">
Adding ng-init="date=ndc.value" does add a default value coming from the controller as expected. But it removes the data binding. The field no longer updates when changing the the input id="setAllEffectiveDates".
How can I have the default values but also have the data binding working?
edit:
updated function I added ng-change:
<input id="setAllEffectiveDates" ng-change="updateEffectiveDates(date)" type="text" data-ng-model="date" value="" class="form-control input-sm">
and then made a function:
$scope.updateEffectiveDates = function (date) {
angular.forEach($scope.ndcs, function (ndc) {
ndc.value = date;
});
console.log($scope.ndcs);
};
THis looks like it updates the model but not the fields on the page.
I suspect that ng-init is creating a new date variable on each new scope created by ng-repeat, so it won't be binding from your controller anymore. If you only need one date, try setting it to an object that exists in your controller:
Controller:
$scope.obj = {
date: null
};
View:
<input ng-init="obj.date=ndc.value">
Edit: Just bind to the date that you already have on each array element:
data-ng-model="ndc.date" ng-change="setOtherDates()"
Final answer:
<input id="setAllEffectiveDates" ng-change="updateEffectiveDates(date)" type="text" data-ng-model="date" value="" class="form-control input-sm">
then:
<input id="effectiveDate" type="text" data-ng-model="ndc.value" class="form-control input-sm">
with function:
$scope.updateEffectiveDates = function (date) {
angular.forEach($scope.ndcs, function (ndc) {
ndc.value = date;
});
console.log($scope.ndcs);
};
Related
What I want to achieve: I want pre-populated data in my form and I also want to use formControlName as I want the data too.
My html file -
<div class="container">
<p class="h4 my-5">Add New Result</p>
<div class="row">
<div class="col">
<form (ngSubmit)="editStudent()" [formGroup]="studentEditForm" name="myForm">
<div class="mb-3">
<label for="roll-no" class="form-label">Roll No.</label>
<input type="number" class="form-control" id="roll-no" name="rollno" formControlName="rollno" value="{{student.rollNo}}" placeholder="{{student.rollNo}}" autocomplete="off" required>
</div>
<div class="mb-3">
<label for="name" class="form-label">Name</label>
<input type="text" class="form-control" id="name" name="name" formControlName="name" value={{student.name}} required>
</div>
<div class="mb-3">
<label for="email" class="form-label">Email address</label>
<input type="email" class="form-control" id="email" name="email" formControlName="email" value={{student.email}} required>
</div>
<div class="mb-3">
<label for="score" class="form-label">Score</label>
<input type="number" class="form-control" id="score" name="score" formControlName="score" value={{student.score}} required>
</div>
<button type="submit" class="btn btn-primary" ng-click="submitForm(myForm.$valid)">Submit</button><button type="submit" class="btn btn-dark mx-4">Clear</button>
</form>
</div>
<div class="col"></div>
<div class="col"></div>
</div>
</div>
In Input Tag, I want to use value attribute so I can get a default value but I get Empty fields and I think it is because formControlName is controlling the data in my form. Is there a way to get pre-populated data using value attribute along with formControlName attribute?
Placeholder attribute works fine but I want a default value.
if you want a default value simply initialize the form with values, for example:
form = new FormGroup({
name: new FormControl('defaultNameValue'),
email: new FormControl('defaultEmailValue')
})
You should be doing it in you component instead of using value attribute. While defining the form example
studentEditForm= new FormGroup({
rollNo: new FormControl(this.student.rollNo)
})
or if student data is not available at the time of definition then use formcontrol.setValue after you initialize the student data something like
this.studentEditForm.controls.rollNo.setValue(this.student.rollNo)
Using the value and the CVA (Control Value Accessor: formControlName, formControl, and ngModel) to control the value of the input will override each other each time you change anyone of them.
Instead, it's better to rely only on one of them. If the CVA is used, then you can pass an initial value (default value) to the form-control while defining it:
studentEditForm = new FormGroup({
score: new FormControl(YOUR_INITIAL_VALUE),
});
For more info, check here how Angular passes the value from CVA to the value property when using both of them:
default_value_accessor.ts
Used value and CVA to control value
try this :
studentEditForm = new FormGroup({
score: new FormControl(VALUE),
});
I'm fetching products from database, they are populating my dropdown.
I have ability to choose a product from dropdown, that product contains unit of measure (liter, kilo, oz etc). So basically when I choose a product from a dropdown I would like to display unit of measure in control below dropdown, like in example above.
Here is my html:
<div class="form-horizontal" action="">
<div class="form-group">
<label class="control-label dash-control-label col-sm-3">Title:</label>
<div class="col-sm-6">
<select class="form-control dash-form-control select2" style="width: 100%;">
<option selected disabled>Search...</option>
<option *ngFor="let ingredient of ingredients;" [value]="ingredient.id">{{ingredient.title}}</option>
</select>
</div>
<div class="col-sm-3">
<button type="button"
class="btn main-content-button mini-add-button"
data-toggle="modal"
data-target="#modal-3">
<i class="fas fa-plus"></i>
</button>
</div>
</div>
<!--Unit of measure-->
<div class="form-group">
<label class="control-label dash-control-label col-sm-3" for="user-lastname">Unit of measure:</label>
<div class="col-sm-4">
<input type="text" class="form-control dash-form-control read-only" placeholder="" value="Liter (L)" readonly>
</div>
</div>
<!--Quantity-->
<div class="form-group">
<label class="control-label dash-control-label col-sm-3" for="user-password">Quantity:</label>
<div class="col-sm-4">
<input type="text" class="form-control dash-form-control" id="user-password" placeholder="">
</div>
</div>
</div><!--End of form horizontal-->
So basically in my input which holds Unit of measure I would like to get unit of measure of selected product and display it there, it's just read only field :)
And here is my typescript code where I'm getting product from DB:
export class ProductIngredientNewComponent implements OnInit {
#Input() ProductId: string;
// Array that will holds all Products which represent ingredients
ingredients: Product[];
id: string;
constructor(public _productsService: ProductService) {
}
ngOnInit() {
// Here I'm getting values from DB and this values are source to dropdown
this._productsService.getAll().subscribe(ing => this.ingredients = ing);
}
}
Do I need to attach event when value in dropdown is selected, to manually set value to some property in typescript and display it in unit of measure, of there is some another more nice and more angular way?
Thanks guys
Cheers
Can you try using the following code and check if your problem is solved. I had the same situation just I had radio buttons in my case. Idea is save your object in value of Option. and assign a model to it which will contain the selected value from select box and bind the same ngmodel to your input.
Hoping it to work for you!
<div class="col-sm-6">
<select class="form-control dash-form-control select2" style="width: 100%;" [(ngModel)]="ingredient.title">
<option selected disabled>Search...</option>
<option *ngFor="let ingredient of ingredients;" [value]="ingredient">{{ingredient.title}}</option>
</select>
</div>
<input type="text" class="form-control dash-form-control read-only" placeholder="" value="Liter (L)" readonly [(ngModel)]="ingredient.title">
With Angular you have the possibility to use the two-way data binding for the selected dropdown item. First declare a property which holds the selected item in the component:
export class ProductIngredientNewComponent implements OnInit {
selectedIngredient: Product;
/* */
}
Then add the ngModel directive to your dropdown and also change the value to be the ingredient itself, instead of ingredient.id:
<select [(ngModel)]="selectedIngredient">
<option selected disabled>Search...</option>
<option *ngFor="let ingredient of ingredients;" [value]="ingredient">
{{ingredient.title}}
</option>
</select>
Then you can easily display the unit in the input field. I also added a check to avoid errors, when the selectedIngredient is not set.
<input type="text" placeholder="Unit" [value]="selectedIngredient && selectedIngredient.unitOfMeasure" readonly>
I have a container that consists of a couple of inputs tag and one select tag. All of them have className, let's call it "contact". In jquery , I am accessing all of them through "contact". Also, there is checkbox that disables when you check it and when toy uncheck it, it empties the input fields and remove disable . The thing i want to do I want when i uncheck the checkbox, I want to set the the input fields as empty string, which i did, but what i did include the selection tag which i do not set as empty string
$("#showCheckoutHistory").change(function(event){
if (this.checked){
$(".contact").attr("disabled","disabled");
}
else {
$(".contact").removeAttr("disabled");
/* here is the problem, how can you empty the value of the input ONlY. Without chnaging the className Javascript and Adding Another name in the HTML
*/
$(".contact").val("");
}
});
<input id="showCheckoutHistory" name="showCheckoutHistory" type="checkbox"/><label for="showCheckoutHistory">check</label>
<div class="container">
<input type="text" value="oo" class="form-control col-xs-10 contact"><br><br>
<input type="text" value="xx" class="form-control col-xs-10 contact"><br><br>
<input type="text" value="yy" class="form-control col-xs-10 contact"><br><br>
<select class="form-control col-xs-10 contact">
<option>A</option>
<option>B</option>
<option selected>C</option>
</select>
</div>
There is error but i dont know what is it
Include the $ reference in your code. That means add
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
in your html
$("#showCheckoutHistory").change(function(event){
if (this.checked){
$(".contact").attr("disabled","disabled");
}
else {
$(".contact").removeAttr("disabled");
/* here is the problem, how can you empty the value of the input ONlY. Without chnaging the className Javascript and Adding Another name in the HTML
*/
$(".contact").each(function(i, el){
if($(el)[0].nodeName != "SELECT"){
$(el).val("");
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input id="showCheckoutHistory" name="showCheckoutHistory" type="checkbox"/><label for="showCheckoutHistory">check</label>
<div class="container">
<input type="text" value="oo" class="form-control col-xs-10 contact"><br><br>
<input type="text" value="xx" class="form-control col-xs-10 contact"><br><br>
<input type="text" value="yy" class="form-control col-xs-10 contact"><br><br>
<select class="form-control col-xs-10 contact">
<option>A</option>
<option>B</option>
<option selected>C</option>
</select>
</div>
</div>
Sorry, I don't have enough reputation to comment.
I tested your code and that works well as you want.
You missed selecting jquery in stackoverflow code snippet.
please check follow code.
If it's not working even after you added jquery script, then please let me know jquery version you used. (don't forget to add jquery cdn or picking jquery library in code snippet editor)
if you want to keep selection of select element please remove the contact class in there like below.
$("#showCheckoutHistory").change(function(event){
if (this.checked){
$(".contact").attr("disabled","disabled");
}
else {
$(".contact").removeAttr("disabled");
/* here is the problem, how can you empty the value of the input ONlY. Without chnaging the className Javascript and Adding Another name in the HTML
*/
$(".contact").val("");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="showCheckoutHistory" name="showCheckoutHistory" type="checkbox"/><label for="showCheckoutHistory">check</label>
<div class="container">
<input type="text" value="oo" class="form-control col-xs-10 contact"><br><br>
<input type="text" value="xx" class="form-control col-xs-10 contact"><br><br>
<input type="text" value="yy" class="form-control col-xs-10 contact"><br><br>
<select class="form-control col-xs-10"> <!-- I removed contact class in here to keep selection -->
<option>A</option>
<option>B</option>
<option selected>C</option>
</select>
</div>
I have a scenario where I have a typeahead on each repeating form element, that contains 5 input fields, everything works well when I select results and populate the input fields but however this doen't update the model (source)
The typeahead:
<input type="search"
ng-model="product"
ng-model-options="{ getterSetter: true }"
typeahead-editable="true"
typeahead-click-open
typeahead-loading="product_Loading"
typeahead-input-formatter="inputFormatter($model)"
typeahead-min-length="0"
typeahead-select-on-exact="true"
typeahead-no-results="noResults"
typeahead-popup-template-url="/app/directives/typeaheadDefaultTemplate.html"
typeahead-popup-template-new="products"
autocomplete="off"
placeholder="Select product"
uib-typeahead="tyh as tyh.name for tyh in typeahead($viewValue, 'products')"
class="form-control no-border-right">
the recipients for the selected element:
<input name="qty" type="number" ng-model="product.qty" class="qty form-control text-right" value="1">
<input name="price" type="number" ng-model="product.price" class="price form-control text-right" placeholder="0.00">
<input name="total" value="0.00" disabled type="number" class="total form-control text-right">
3rd input needs an ng-model attribute.
On the typeahead, the ng-model refers to the search query. If you want to update the product object and have it flow down to the other inputs, you will have to do that programmatically, either on select or on focus.
In your typeahead, update the model to productSearchModel, then add the following attribute
typeahead-on-select="onSelect($item, $model, $label, $event); productSearchModel = '';"
then add something like this to your controller
$scope.onSelect = function (item, model, label, event) {
product = model;
};
which will fire when a user selects an option.
Hi I have two input fields. input field A(drop-down) and input field B. Both of them are posting same value (same ng-model). What I need to achieve is when the user select one option from the dropdown button the second input field need to cleared. How can I do that using AngularJS? Am very new to AngularJS. Thanks in advance.
<table align="center">
<tr>
<td>
<div class="input-group">
<span class="input-group-addon"><b>BB</b></span>
<input class="form-control" type="input" ng-model="final_data.bb" readonly>
</div>
</td>
<p align="center" ng-show="processing['update_ms']" ng-class="processing['update_mst'].class" ng-cloak>
{{ processing['update_ms'].msg }}
</p>
<td>
<div class="input-group">
<span class="input-group-addon"><b>InputA</b></span>
<select class="form-control" ng-change="get_mass(); disableMass() " ng-model="final_data.mas" ng-options="m as m for m in maslist" required ng-cloak>
</select>
</div>
</td>
<td>
<div class="input-group">
<span class="input-group-addon"><b>InputB*</b></span>
<input class="form-control" ng-disabled="isSelected" ng-model="final_data.mas" type="input">
</div>
</td>
</tr>
</table>
How about to create 2 different models for select input and input field and initialize them by nil. So you can:
<select ng-model='selectModel' ng-disabled='inputModel'>
...
</select>
<input type='text' ng-model='inputModel' ng-disabled='selectModel' />
And if you need to change original model by changing select and input models:
html
<select ng-model='selectModel' ng-disabled='inputModel' ng-change=syncModel(selectModel)>
...
</select>
<input type='text' ng-model='inputModel' ng-disabled='selectModel' ng-change=syncModel(selectModel)/>
js
$scope.originalModel = null;
$scope.syncModel = function (value) {
$scope.originalModel = value;
}
UPDATE:
If you want to clear another field:
$scope.syncModel = function (value) {
$scope.originalModel = value;
//clearing
if (value == $scope.inputModel)
$scope.selectModel = null;
else
$scope.inputModel = null;
}
Dirty but easy
UPDATE:
Your code:
<table align="center">
<tr>
<td>
<div class="input-group">
<span class="input-group-addon"><b>BB</b></span>
<input class="form-control" type="input" ng-model="final_data.bb" readonly>
</div>
</td>
<p align="center" ng-show="processing['update_ms']" ng-class="processing['update_mst'].class" ng-cloak>
{{ processing['update_ms'].msg }}
</p>
<td>
<div class="input-group">
<span class="input-group-addon"><b>InputA</b></span>
<select class="form-control" ng-change="get_mass(); syncModels(selectModel) " ng-model="selectModel" ng-options="m as m for m in maslist" required ng-cloak ng-disabled="inputModel">
</select>
</div>
</td>
<td>
<div class="input-group">
<span class="input-group-addon"><b>InputB*</b></span>
<input class="form-control" ng-disabled="selectModel" ng-model="inputModel" ng-change="syncModels(inputModel)" type="input">
</div>
</td>
</tr>
</table>
js
$scope.selectModel = null;
$scope.inputModel = null;
$scope.syncModels = function (value) {
$scope.final_data.mas = value;
//clearing
if (value == $scope.inputModel)
$scope.selectModel = null;
else
$scope.inputModel = null;
}
It doesn't make sense.
ng-model is real time representation of input fields' displayed value. At least for text input, the displayed text is always equal to its ng-model value.
I also have hard time figuring out your use case. What happens to the dropdown when the user type in input field?