How to manage nested formGroup in Angular? - angular8

I have created a dynamic form using formGroup and formArray, and need to get repItems inside the repForm in HTML, but got the following error:
ERROR TypeError: Cannot read property 'get' of undefined
at Object.eval [as updateDirectives]
How to resolve it without using formBuilder?
My code:
ngOnInit() {
this.quizForm = new FormGroup({
items: new FormArray([new FormGroup({
question: new FormControl('',Validators.required),
repOne: new FormControl(''),
repForm: new FormGroup({
repItems:new FormArray([new FormGroup({
rep: new FormControl('',Validators.required)
})])
})
})])
})
}
<form [formGroup]="quizForm" #formDir="ngForm">
<div formArrayName="items" *ngFor="let item of quizForm.get('items').controls; let i = index;">
<div [formGroupName]="i">
<div class="form-group">
<label for="question">Question</label>
<input id="question" class="form-control" formControlName="question">
</div>
<div formGroupName="repForm">
<div formArrayName="repItems"
*ngFor="let repItem of repForm.get('repItems').controls; let r = repIndex;">
<div [formGroupName]="r">
<div class="form-group">
<label for="rep">Response</label>
<input id="rep" class="form-control"
formControlName="rep">
</div>
<button type="submit" class="btn btn-default"
(click)='removeRepItem(r)'>RemoveForm</button>
<button type="submit" class="btn btn-default" (click)='addRepItem()'>addForm</button>
</div>
</div>
</div>
<button type="submit" class="btn btn-default" (click)='removeItem(i)'>RemoveForm</button>
</div>
</div>
</form>

Related

How to display validation summary below the input controls?

I have the following form:
<form asp-controller="Manage" asp-action="RemoveDetails" method="post" class="form-horizontal">
#if (Model.RequirePassword)
{
<div id="password-container">
<div class="col-md-6">
<div class="form-group">
<label asp-for="Password"></label>
<input asp-for="Password" class="form-control" id="password" autocomplete="current-password" aria-required="true" />
<small>
<span asp-validation-for="Password" class="text-danger"></span>
</small>
</div>
</div>
</div>
}
<div class="col-6">
<hr class="mt-2 mb-3">
<button type="submit" class="btn btn-style-1 btn-danger">Confirm</button>
</div>
<div class="row">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
</div>
</form>
If I leave the password empty, a validation message (the model uses DataAnnonations) is displayed right below the control. This is fine.
If I enter the wrong password, the Post action validates it and adds an error to the ModelState. This error is displayed below the form.
Is it possible to display such model errors below the relevant controls?
Try this code in Controller: ModelState.AddModelError("Password", "validation summary error."); The error message won't display in <div asp-validation-summary="ModelOnly"></div>, but it can display error message in #Html.ValidationSummary(false, "", new { #class = "text-danger" }).
<form asp-controller="Home" asp-action="RemoveDetails" method="post" class="form-horizontal">
<div id="password-container">
<div class="col-md-6">
<div class="form-group">
<label asp-for="Password"></label>
<input asp-for="Password" class="form-control" id="password" autocomplete="current-password" aria-required="true" />
<small>
#*<span asp-validation-for="Password" class="text-danger"></span>*#
#Html.ValidationSummary(false, "", new { #class = "text-danger" })
</small>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label asp-for="Description"></label>
<input asp-for="Description" class="form-control" id="description" autocomplete="current-password" aria-required="true" />
<small>
<span asp-validation-for="Description" class="text-danger"></span>
</small>
</div>
</div>
</div>
<div class="col-6">
<hr class="mt-2 mb-3">
<button type="submit" class="btn btn-style-1 btn-danger">Confirm</button>
</div>
<div class="row">
<div asp-validation-summary="ModelOnly"></div>
</div>
</form>
[HttpPost]
public IActionResult RemoveDetails(RemoveDetail rdl)
{
if(ModelState.IsValid)
{
var pwd = rdl.Password;
//do something here and find the password is wrong
//code below won't display error message in <div asp-validation-summary="ModelOnly" class="text-danger">
//but can display error message in #Html.ValidationSummary(false, "", new { #class = "text-danger" })
ModelState.AddModelError("Password", "validation summary error.");
return View(rdl);
}
return View(rdl);
}

How to focus click on input vue

how do i focus input with a button onClick?
<div class="form-group"
v-for="(file, i) in registerData.requiredDocuments"
:key="`file-${i}`">
<label for="npwp" class="text-muted"> {{file.name}} </label>
<input type="file"
:name="file.name"
class="form-control-file"
:id="file.name"
:accept="file.name === 'Logo' ? `image/png, image/jpg, image/jpeg` : `application/pdf`">
<div class="d-flex">
<button class="btn btn-primary" type="button">Choose File</button>
</div>
</div>
i was hoping by clicking the 'choose file' button it would trigger the input. I've tried
// the input
<input :ref="file.name" type="file">
// the button
<button #click="$refs.file.name.focus()">Choose File</button>
but what i get is the name is undefined anyone knows how to fix this?
I had similar problem before, Here is how and did it.
<template>
<div>
<div class="form-group" v-for="(file, i) in registerData.requiredDocuments" :key="`file-${i}`">
<label for="npwp" class="text-muted"> {{file.name}} </label>
<input type="file" :ref="'file' + i" :name="file.name" class="form-control-file" :id="file.name"
:accept="file.name === 'Logo' ? `image/png, image/jpg, image/jpeg` : `application/pdf`">
<div class="d-flex">
<button #click.prevent="setFileFocus(i)" class="btn btn-primary" type="button">Choose File</button>
</div>
</div>
</div>
</template>
<script>
export default {
methods: {
setFileFocus(index) {
this.$nextTick(function(){
this.$refs[("file" + index)][0].focus()
})
}
}
}
</script>
I called focus on nexttick. Hope my answer will be helpful

IFormFile is null, Razor

I'm trying to bind an image uploading but facing the problem with sending this image to the controller.
I'm using Razor and .net core 2.2.
My Controller
[HttpPost(nameof(MealController))]
[Authorize(Roles = UserRoles.Moderator)]
public IActionResult Update(MealModel meal, IFormFile pic)
{
if (ModelState.IsValid)
{
try
{
var changedMeal = _mapper.Map<MealModel, MealDTO>(meal);
_mealService.Update(changedMeal, pic);
}
catch (Exception e)
{
return NotFound();
}
return RedirectToAction("Index");
}
return View(meal);
}
My form
<form class="form" method="post" asp-controller="Meal" asp-action="Update">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Продукт</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="product">
<div class="product-img">
<div class="selector">
<img src="#Model.ImagePath" class="img-thumbnail" id="selectedImg" alt="Product Image"/>
<div class="form-group">
<input type="file" class="custom-file-input" id="pic-input" name="pic"
onchange="readURL(this, 'selectedImg')">
#* <label class="custom-file-label" for="pic-input"></label> *#
</div>
</div>
</div>
<div class="product-info">
<div class="form-group name">
<label for="name">Назва продукту</label>
<input class="form-control" type="text" placeholder="Назва" id="name" name="name" asp-for="Name"
value="#Model.Name">
</div>
<div class="form-group">
<label for="name">Ціна</label>
<input class="form-control" placeholder="Price" id="price" type="number" asp-for="Price"
value="#Model.Price">
</div>
<div class="form-group">
<label for="name">Вага</label>
<input class="form-control" id="weight" type="number" asp-for="Weight"
value="#Model.Weight">
</div>
<div class="comments">
<textarea class="form-control" rows="3" cols="5" placeholder="Склад" asp-for="Description" value="#Model.Description"></textarea>
</div>
<input type="hidden" asp-for="MealGroupId" value="#Model.MealGroupId"/>
<input type="hidden" asp-for="Id" value="#Model.Id"/>
#* <input type="hidden" asp-for="ImagePath" value="#Model.ImagePath"/> *#
</div>
</div>
</div>
<div class="modal-footer">
<div class="action-button">
<button type="submit"
class="btn btn-success ok-button">
<span>Додати</span>
</button>
<button type="reset"
class="btn btn-danger remove-button">
<span>Відмінити</span>
</button>
</div>
</div>
</div>
</form>
When I debug, IFormFile is always null. I tried using [FromForm] but it didn't help. I googled and found out that my name in form and parameter name was different but it had effect. Could you, please give me a little hint on how I can solve it. Thank you and have a good day!
You have to specify <form>'s enctype attribute set to multipart/form-data to be able to send files to server
<form class="form" method="post" asp-controller="Meal" asp-action="Update" enctype="multipart/form-data">

How do i take radio value checked in vuejs?

I have this code so far, i try to take the value from radio button.I can take from v-model value but with radio i have some problems.For example if i have more radio buttons how i can take the checked one.
new Vue({
el:'#root',
data:{
removelines: [
{value:'a'},
{value:'b'}
]
},
methods:{
insert:function(){
let vueIn = this;
axios.post('/vue', {removelines: vueIn.removelines.value}).then(
function(response){
vueIn.removelines = response.data.removelines.value;
}
).catch(function(error){ console.log(error.message); });
}
}
});
html code here:
<div class="card-block">
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-warning active">
<input v-model="removelines" name="removelines" type="radio" class ="cheker" autocomplete="off" v-bind:value="a" checked>
Yes
</label>
<label class="btn btn-warning">
<input v-model="removelines" name="removelines" type="radio" class ="cheker" v-bind:value="b">
No
</label>
</div>
</div>
Check this working sample, please.
new Vue({
el: '#root',
data: {
removelines: 'b'
}
});
<script src="https://unpkg.com/vue#2.4.2/dist/vue.js"></script>
<div id="root">
<div class="card-block">
{{ removelines }}
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-warning active">
<input v-model="removelines" name="removelines" type="radio" class ="cheker" autocomplete="off" v-bind:value="'a'" checked>
Yes
</label>
<label class="btn btn-warning">
<input v-model="removelines" name="removelines" type="radio" class ="cheker" v-bind:value="'b'">
No
</label>
</div>
</div>
</div>

Using vue js with selectpicker

I'm using Vue.js to add multiple rows, each row contain two datetimepicker inputs and a bootstrap-select.
My problem is when I fill the inputs and click to add a new row the previous ones clear out, the reason is each time I add a new row I'm using setTimeout to referesh the selectpicker and the datetimepicker.
So I want to know if there is a way to trigger the last added element them without refreshing the previous ones.
Here is my code :
HTML
<div class="cols" id="app">
<ul style="list-style-type: none;">
<li>
<button style="float: right;margin-right: 20px;margin-top: 5px;" type="button" class="btn btn-success btn-xs" v-on:click="addRow()">
<i class="fa fa-plus"></i> Ajouter
</button>
</li>
<li v-for="(row, id) in rows">
<div class="form-inline cp-out" style="padding-bottom: 9px;border-radius:4px;background-color:white;margin-left:-20px;display:inline-block;width:100%;margin-top:10px;">
<div class="col-md-3">
<label :for="['time_start'+id]" class="control-label">start time</label>
<div class="input-group date form_time" style="width:100%;" data-date="" data-date-format="hh:ii" :data-link-field="['time_start'+id]" data-link-format="hh:ii">
<input v-model="row.startTime" :name="'rows['+id+'][startTime]'" class="form-control" :id="['startTime' + id]" size="16" type="text" value="" >
<span class="input-group-addon"><span class="glyphicon glyphicon-time"></span></span>
</div>
</div>
<div class="col-md-3">
<label :for="['time_end'+id]" class="control-label" style="margin-left:7px;">end time</label>
<div class="input-group date form_time" style="width:100%;" data-date="" data-date-format="hh:ii" :data-link-field="['time_end'+id]" data-link-format="hh:ii">
<input v-model="row.endTime" :name="'rows['+id+'][endTime]'" class="form-control" :id="['endTime'+id]" size="16" type="text" value="" >
<span class="input-group-addon"><span class="glyphicon glyphicon-time"></span></span>
</div>
</div>
<div class="col-md-4">
<div class="form-group select_group" style="margin-left:5px;">
<label :for="['status' + id]" class="control-label">Status</label>
<select data-width="100%" v-model="row.status" :name="'rows['+id+'][status]'" :id="['status' + id]" class="select_picker" data-live-search="true" multiple >
<option value="Status 1">Status 1</option>
<option value="Status 2">Status 2</option>
</select>
</div>
</div>
<div class="col-xs-1">
<button type="button" class="btn btn_delete btn-xs btn-danger" v-on:click="delRow(id)">
<i class="fa fa-remove"></i> delete
</button>
</div>
</div>
</li>
</ul>
</div>
JS
app = new Vue({
el: '#app',
data: {
rows: []
},
methods: {
addRow: function () {
this.rows.push({startTime: '', endTime: '', status: []});
setTimeout(function () {
$('.select_picker').selectpicker('refresh');
$('.form_time').datetimepicker({format: 'LT'});
}.bind(this), 10);
},
delRow: function (id) {
this.rows.splice(id, 1);
}
},created:function() {
this.addRow();
}
});
This is the example : https://jsfiddle.net/rypLz1qg/9/
You really need to write a wrapper component. Vue expects to control the DOM and not to have you making DOM-changing things like the *picker calls at arbitrary times. However, a component gives you the opportunity to tell your component how to interact with the DOM in each of its lifecycle hooks so that its behavior can be consistent. See the JavaScript tab on the wrapper component example page.