Angular 8 Reactive Form, Set Default Selected Option - angular-material

Sorry am struggling to set default selected option in drop-down list when I open Dialog Model Form.
I have two model
department
employee
Also i have two component which is employee and employee-list, employee-list component is responsible for load all list of employee in a table and employee component is responsible to load singe employee..
In employee-list i set click event which call edit function and populate selected row in a form for editing purpose.. but when form opne it open with other filed by select option does not appear i do not know why.
employee.ts
dept: any;
ngOnInit() {
this.loadAllDept();
this.selected = this.employeeService.form.get('department').value;
}
loadAllDept(){
this.employeeService.getAllDepartments().subscribe(
data => {
this.dept = data;
}
);
}
And my employee.html
<mat-grid-tile>
<div class="reg-control-container">
<mat-form-field>
<mat-select [(value)]="selected" formControlName="depatment" placeholder="Class">
<mat-option>None</mat-option>
<ng-container>
<mat-option *ngFor="let d of dept" value="{{d.id}}"> {{ d.name }}</mat-option>
</ng-container>
</mat-select>
</mat-form-field>
</div>
</mat-grid-tile>
but it does not set default value to a drop-down list.
Like the following picture show I can output both default selected and list of option but i can not set it.
as shown below

Take a look at this example, https://stackblitz.com/edit/angular-5short
Keep in mind that you need to bind the value of the option using the property binding syntax Angular provides, encasing the property you want to assign the value to in square brackets ([]). With that, as long as you pass the same value to the FormControl you want, it should apply the default option correctly.

Related

Rails count number of checkboxes in a view before posting

I have little knowledge of Javascript, but I think it might be the only way to make things work in my problem.
I am using rails 5.
I basically have checkboxes in a view that represent a price, and every time I check or uncheck one, I would like to update the total price for that view (that I then pass in a hidden_field and a post request).
I'm guessing that what I have to do is get an onclick event going everytime I check or uncheck a box, and update a variable that I then show in the view.
I've found something that looks very similar to my case, but unfortunately I'm unable to reproduce it: Rails Jquery compute total from selected checkboxes in a table
I have my checkboxes with a class "checkbox-count", and I can send an alert everytime I check them, but that's about all I have so far...
Your help would be very appreciated!
This could be handled on the server side by getting an array(checkbox names are all the same array value) of the checked boxes values in a controller action and adding the values together there, maybe you have a reason not to though?
Otherwise this is more of a javascript question, but it could be handled with some vanilla javascript like this maybe:
// a quick custom function for calculating total values of all checked checkboxes in a given form
function calcFormCheckedBoxesTotal(form) {
total = 0;
form.querySelectorAll("input[type='checkbox']:checked").forEach(checked_box => {
total += parseInt(checked_box.getAttribute("value"));
});
return total;
}
// get all form checkbox inputs to be used
checkboxes = document.querySelectorAll("form input.checkbox-count");
// loop through all given form checkbox inputs so we can...
checkboxes.forEach(checkbox => {
// ... add click event listener to each checkbox
checkbox.addEventListener('click', event => {
// ... use my custom function to calculate totals of all checked boxes in the parent form of currently clicked on checkbox and store in "total" variable
total = calcFormCheckedBoxesTotal(event.target.parentElement);
// ... change value of my text input with id="total_price" to show total of checked boxes. Change the target of the querySelector to whatever you want to update(your hidden field) with the total.
document.querySelector("#total_price").value = total;
});
});
<form>
<input type="checkbox" class="checkbox-count" name="price[]" value="25"><label>$25</label><br>
<input type="checkbox" class="checkbox-count" name="price[]" value="50"><label>$50</label><br>
<input type="checkbox" class="checkbox-count" name="price[]" value="100"><label>$100</label><br>
<input type="text" id="total_price" name="total_price" value="0">
</form>

ViewModel binding without SelectList in ASP.NET MVC

In my ASP.NET Core application, I have an ASP.NET MVC View which displays a list of products. (I guess this applies to other versions of MVC as well).
When I select an item from this list and submit the page, I want the selected product ID to be bound to a ViewModel property in the action method of the controller. I am using POST for this.
I do NOT want to use SelectList for rendering the list of products due to some formatting issues. Therefore I am looping over the list in my view.
How can I bind the selected product with the ProductId property of the inbound ViewModel object?
It's unclear what you mean by "select an item from this list and submit the page". Are you picking an item, potentially filling out more fields, and then submitting the whole shebang, or does picking an item constitute submitting the form. Depending on the situation there's a few approaches:
If picking an item submits the form, then you can simply make the "Select" button a submit button and give it a name and value. For example:
Item 1 <button type="submit" name="ProductId" value="1">Select</button>
Whichever "Select" button is clicked, then, will have its value posted as ProductId.
If you need to pick an item while remaining on the page to fill out other fields, then you can use radio buttons as an alternative to a select list. This is similar to approach above, except you will not instantly post the form. Your inputs would look similar though:
<label>
<input type="radio" name="ProductId" value="1"> Item 1
</label>
<label>
<input type="radio" name="ProductId" value="2"> Item 2
</label>
...
Finally, if you need to not instantly submit and you do not want to use radio buttons either, then your only real option is using JavaScript to set a hidden input. You would bind to the click event of your "Select" button or whatever and then set a hidden input with name="ProductId" to the appropriate value. Then, when you finally submit the form, the value of the hidden input will be posted as ProductId.

MVC6 select tag helper for edit applying current value

I have a viewmodel with a state dropdownlist.
The form is being populated from a database and I everything works except I dont know how to apply the current value for state as the default value for the select helper tag?
This is the CSHTML for the select:
<select asp-for="State" asp-items="#Model.StatesList" > </select>
This provides the all the states when you do a dropdown however is there a way to set the value to the current value for Model eg #Model.state so if you dont select any new dropdown value it takes the original value for the record?

how to set radio button for edit in grails

I am using grails 2.1.1 I have a domain where I want to save religion of member. I am saving it there is no problem. But when I go to edit page then it does not checked the original value.Suppose I am saving a religion for Buddhist and at the time of edit I want to be checked the value of it. But it is checking for Muslim. I want the field to be checked on edit page. Can anyone please help me on this please ??!!! Here are my attempts below ::
my domain class >>>
class RadioButton {
String religion
static constraints = {
}
}
my form page >>>
<div class="fieldcontain ${hasErrors(bean: radioButtonInstance, field: 'religion', 'error')} ">
<label for="religion">
<g:message code="radioButton.religion.label" default="Religion"/>
</label>
<g:radio name="religion" value="muslim" checked="checked"/> Muslim <br/>
<g:radio name="religion" value="hindu"/> Hindu<br/>
<g:radio name="religion" value="christian"/> Christian<br/>
<g:radio name="religion" value="buddhist"/> Buddhist
</div>
You may want to consider the radioGroup tag within Grails instead of manually authoring your radio buttons.
However, if you decide to continue manually authoring your radio buttons you will need to account for selecting the current value. For example:
<g:radio name="religion" value="muslim" checked="${radioButtonInstance?.religion.equals('muslim')}"/>
In the above example you will notice that the checked attribute is being set to a boolean value (which is correct according to the documentation).
I think radioGroup is by far a better solution for you as you are using grails.
They main problem is that you are not passing the currently set religion to the GSP. There is nothing telling the radio group which religion has already been set by the user, instead Muslim has been hard-coded with the checked="checked".
Judging from your first line which sets the class of the div if the bean has an error, I assume you can access the currently set religion from the radioButtonInstance. Using the radioGroup tag you pass the currently set value as ${radioButtonInstance?.religion}, then we set the values and the labels you need, as shown:
<g:radioGroup name="religion"
values="['Muslim', 'Hindu', 'Christian', 'Buddhist']"
labels="['Muslim', 'Hindu', 'Christian', 'Buddhist']"
value="${radioButtonInstance?.religion}">
<p>${it.label}: ${it.radio}</p>
</g:radioGroup>
I would, however, suggest that you set the available religions as an enum class rather than hard coding it onto the GSP, as you might want to reuse it. You could then pass it as a variable in the model through the controller, calling it, for example, religions, then your radioGroup would look like:
<g:radioGroup name="religion"
values="${religions}"
labels="${religions}"
value="${radioButtonInstance?.religion}">
<p>${it.label}: ${it.radio}</p>
</g:radioGroup>

MVC Unobtrusive validation for a dropdown using knockout.js?

I am using knockout.js to populate a dropdown:
<select data-bind="options: AvailableUsers, optionsText: 'DisplayName', value: SelectedUser, optionsCaption: '-- Select a User --'" data-val="true" data-val-required="You must select a user." id="SelectedUser" name="SelectedUser"></select>
<span class="field-validation-valid" data-valmsg-for="SelectedUser" data-valmsg-replace="true"></span>
and I am registering the validator to the form and having it called on the submithandler (I dont think this is related to the problem since the validation is executing):
$.validator.unobtrusive.parse("#UserProfileCreation");
$("#UserProfileCreation").data("validator").settings.submitHandler = mappedModel.save;
However when trying to submit the page, it always acts like the dropdown has no selected value. Even when I confirm via console that SelectedUser has a value. I have successfully done the same thing in other pages for textareas like so:
<textarea style="width: 100%; height: 50px; min-height: 30px;" name="GroupReply" id="GroupReply" data-bind="value: GroupReply" data-val="true" data-val-required="You must enter a reply."></textarea><br/><span class="field-validation-valid" data-valmsg-for="GroupReply" data-valmsg-replace="true"></span>
And that works fine. So I am not sure what I am missing for the dropdown, but whether I select an option or not, it keeps acting like it's blank and bringing up the validation error message. What am I missing?
I figured it out and it was quite simple due to my lack of understanding of how knockout handles dropdown's selected values.
My AvailableUsers in the KO View Model consisted of a list of KeyValueModels which were based off a C# MVC class (converted using the KO mapping plugin):
public class KeyValueModel{
public Guid Id {get; set;}
public string DisplayName {get; set;}
}
I simply needed to add optionsValue: 'Id' to the data-bind attribute of the dropdown. However it should be noted that this only works because I am passing a Guid as the SelectedUser property of the MVC View Model in the action parameter.
There have been times where I wanted to pass an entire javascript object that the dropdown selection represents to the MVC view model, in those cases this solution wouldn't work.
Note in console, if you do NOT have the optionsValue: 'Id' you select an option from the dropdown and type mappedModel.SelectedUser() you get:
Object {Id: "adb9ae2d-01c8-468d-96e6-06ec39039e29", DisplayName: "Johnson, John"}
Because knockout can store the whole selected object. HOWEVER, knockout does not set ANY value to the options in the dropdown in the actual HTML markup, they are all null (which is why the validation was failing).
If you do add optionsValue: 'Id' and type mappedModel.SelectedUser() into console, then you would simply get:
"adb9ae2d-01c8-468d-96e6-06ec39039e29"
Which for my purposes on this page is fine. As mentioned if you wanted to pass an entire object to the MVC action based on that selection, this setup would not work. You would probably have to do something like setup a hidden field and set it's value to the SelectedUser().Id and put the validation on that hidden field.

Resources