Angular 5 template-driven form for creating and editing close issue (ng-bootstrap modal) - angular5

I have such Angular 5 template-driven form made with ng-bootstrap modal
<button type="button" class="close" (click)="activeModal.close()"
aria-label="Close">
<span aria-hidden="true">x</span>
</button>
<form (ngSubmit)="editMode ? editBoard(board) : addBoard(newBoard.value)"
#newBoard="ngForm"
id="newBoard"
name="newBoard"
novalidate>
<div class="form-group">
<label>Board name</label>
<input type="text"
*ngIf="editMode"
class="form-control"
name="name"
#name="ngModel"
[ngModel]="board?.name"
(input)="changeName(board, name.value)"
placeholder="Enter a board name (required)"
autofocus
required>
<div *ngIf="name.touched && name.errors">
<div *ngIf="name.errors.required" class="alert alert-danger">Board name is required</div>
</div>
</div>
</form>
I want to use it for create and for edit. While adding and editing it's Ok but when I'm closing empty form modal (open and close) with "Close" or "x" buttons I have an error when input into field:
ERROR TypeError: Cannot set property 'name' of undefined
Here is a function to open a modal
public openBoardModalToAdd(): void {
const ref = this.modal.open(BoardModalComponent,
{
keyboard: false,
backdrop: 'static',
size: 'lg'
}
);
ref.componentInstance.board = {name: ''};
ref.result.then(board => this.boards = [...this.boards, board]);
}
How I can fix this?

Related

Vue's reactivity not triggered when using Bootstrap 5's alert div

Vue's reactivity not triggered when using Bootstrap 5's alert div.
See my code:
<template>
<div>
<div
v-if="alertICDMsg!==''"
id="alertICDCode"
class="alert alert-info alert-dismissible fade show"
role="alert"
>
<i class="fa-solid fa-lightbulb" />
<strong> Note!</strong> <span v-html="alertICDMsg" />
<button
type="button"
class="btn-close"
data-bs-dismiss="alert"
aria-label="Close"
/>
</div>
<div class="input-group mb-3">
<div class="col-xs-1">
<input
id="ICDCode"
v-model="editing_icdCode"
class="form-control"
placeholder="ICD Code"
aria-label="ICD Code"
#input="ICDCodeSearchRequested"
>
</div>
<input
id="Diagnosis"
v-model="editing_diagnosis"
type="text"
class="form-control"
placeholder="Diagnosis"
aria-label="Diagnosis"
aria-describedby="basic-addon1"
list="icdsearchlist"
#change="SelectedDiagnosisTextOption"
#input="ICDTextSearchRequested"
>
<datalist id="icdsearchlist">
<option
v-for="(disease_option, index) in icd_diagnosis_options"
:key="index"
>
{{ disease_option }}
</option>
</datalist>
<button
id="btnAddDiagnoses"
href="#"
class="btn btn-primary mx-1"
#click="AddDiagnosis"
>
<i class="fal fa-plus-circle" />
</button>
<button
id="btnCopyPreviousDiagnoses"
href="#"
class="btn btn-primary BtnSaveGroup mx-1"
>
<i class="far fa-history" />
</button>
<button
id="quickbill"
class="btn btn-primary mx-1"
>
<i class="fas fa-search-plus" />
</button>
<button
id="clearICD"
class="btn btn-danger mx-1"
#click="ClearICDFields"
>
<i class="fad fa-times-circle" />
</button>
</div>
</div>
<template>
<script>
export default {
data() {
return {
alertICDMsg:"",
};
},
watch: {
alertICDMsg: {
handler(val) {
console.log(`Val for alertICDMsg changed to :${val}`);
},
immediate: true,
deep: true,
},
},
methods: {
ICDCodeSearchRequested() {
console.log(`Search by ICD code`);
this.alertICDMsg="Searching in ICD Code box will search only by code. To search by a diagnosis name, type in the Diagnosis box."
console.log(`alertICDMsg is ${this.alertICDMsg}`);
setTimeout(function() {
console.log(`Dismissing alert`);
this.alertICDMsg='';
console.log(`alertICDMsg is ${this.alertICDMsg}`);
}, 5000);
},
},
}
</script>
Console log:
Search by ICD code
SubClinicalBlock.vue?d801:291 alertICDMsg is Searching in ICD Code box will search only by code. To search by a diagnosis name, type in the Diagnosis box.
SubClinicalBlock.vue?d801:220 Val for alertICDMsg changed to :Searching in ICD Code box will search only by code. To search by a diagnosis name, type in the Diagnosis box.
SubClinicalBlock.vue?d801:293 Dismissing alert
SubClinicalBlock.vue?d801:298 alertICDMsg is
The problem is that after 5 seconds, though the value of the variable changes, the alert is still visible.
I checked some similiar questions, and have seen this happening when bootstrap's javascript wasnt loaded. But for me, Bootstrap v5.0.1 JS is being loaded from the CDN and appears in the sources tab in Chrome.
Try to change the function inside of setTimeout to arrow function like this
setTimeout(() => { // code here })
The this inside of setTimeout(function () => {}) reference to the wrong context (the function itself) instead of the Vue component.
The arrow function doesn't have the this binding so when you use the arrow function the this keyword will reference the Vue component and change the state.
More info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

boostrap vue modal not hide when click ok button with validation

I want to add validation to a modal window, I need a behavior in which when the OK button (form submission) is clicked, validation would take place, and if the result is negative, the window should not close
my modal
<b-modal
size="lg"
id="modalToRepair"
title="Add Problem"
title-class="font-18"
centered
body-class="p-4"
no-close-on-backdrop
no-close-on-esc
#ok="onClickModalRepair"
>
<div class="row">
<div class="col-lg-12">
<div class="form-group row">
<label class="col-4 col-form-label">
Repair Problem
<span class="text-danger">*</span>
</label>
<div class="col-8">
<input
v-model="theProblem"
type="text"
class="form-control"
placeholder="Input problem"
name="theProblem"
:class="{
'is-invalid': typesubmit && $v.theProblem.$error
}"
/>
<div
v-if="typesubmit && $v.theProblem.$error"
class="invalid-feedback"
>
<span v-if="!$v.theProblem.required">Requred field.</span>
</div>
</div>
</div>
</div>
</div>
</b-modal>
and my methods
Vue.js
methods: {
onClickModalRepair() {
this.typesubmit = true;
this.$v.$touch();
if (this.$v.$invalid) {
this.$bvModal.show("modalToRepair"); // not work - modal hide
//code for not hide this modal
return;
}
}
},
validations: {
theProblem: {
required
}
}
is it possible?
The method used in the #ok event, is passed an event, which you can call .preventDefault() on, if you want to prevent the modal from closing.
onClickModalRepair(bvModalEvt) {
this.typesubmit = true;
this.$v.$touch();
if (this.$v.$invalid) {
bvModalEvt.preventDefault();
return;
}
}
You can see an example of this on the docs.

VueJs v-Model Binding with Hidden Component not working

I am developing a SPA application in Vue. I have a wizard in the wizard I have a component for each step. All the components are adding at the start and their mounted and created method/event is executing when the application starts.
I am using the event bus & when I move to the next step of wizard I emit the event and catch the event on the respective step.
Note: Component is hidden at the start and when it shows it will not have the updated data or even data in input fields.
Code of the component of the 2nd step is
<template>
<section>
<div class="container">
<form class="form-horizontal">
<div class="row form-group">
<label class="col-sm-3 control-label" for="marshaCode">MARSHA Code:</label>
<div class="col-sm-4">
<input type="text" class="form-control field-ml-15" v-model="marshaCode" placeholder="Enter Marsha Code" readonly />
<input type="text" class="form-control field-ml-15":value="marshaCode" placeholder="Enter Marsha Code" readonly />
<p>{{marshaCode}}</p>
</div>
</div>
</form>
</div>
</section>
</template>
<script>
import { EventBus } from "../../shared/eventbus.js";
export default {
data() {
return {
marshaCode:"On Load Code"
}
},
mounted() {
EventBus.$on('showSurvey', () => {
this.marshaCode="On Show Code"
});
},
}
</script>
Now when this component will show the P tag will have "On Load Code" But in both the fields there will be no data.
How can I rebind, re-render or update the data?
Use vue to show/hide the component using v-if or v-show. It can't do it's job if another library is messing with the DOM.
<section v-if='showMyComponent'>
or
<div class="col-sm-4" v-if='showMyComponent'>
<input type="text" class="form-control field-ml-15" v-model="marshaCode" placeholder="Enter Marsha Code" readonly />
<input type="text" class="form-control field-ml-15":value="marshaCode" placeholder="Enter Marsha Code" readonly />
<p>{{marshaCode}}</p>
</div>
And set showMyComponent to a computed or data property. Then remove the logic to show/hide from your other library.
You can simply add this.marshaCode="On Show Code" when mounted.
mounted() {
this.marshaCode="On Show Code"
console.log(EventBus)
EventBus.$on('showSurvey', () => {
this.marshaCode="On Show Code"
});
}
An example: https://codesandbox.io/embed/vue-template-8l2lg.

Why still adding even with validation form?

When I click the button on my modal with an empty field on my input its give me an undefined value on my console. And when I put a value on my input and click the button it is adding to my database. The problem is even the empty field or the undefined value are also adding to my database and the sweetalert is not working. I want to prevent the empty field adding to my database and prevent the undefined. Can somebody help me?
//start of method
checkForm: function(e) {
if (this.category_description) {
return true;
}
this.errors = [];
if (!this.category_description) {
this.errors.push('Category required.');
}
e.preventDefault();
},
addCategory : function() {
axios({
method : "POST",
url : this.urlRoot + "category/add_category.php",
data : {
description : this.category_description
}
}).then(function (response){
vm.checkForm(); //for FORM validation
vm.retrieveCategory();
console.log(response);
swal("Congrats!", " New category added!", "success");
vm.clearData();
}).catch(error => {
console.log(error.response);
});
},
//end of method
<form id="vue-app" #submit="checkForm">
<div class="modal" id="myModal" > <!-- start add modal -->
<div class="modal-dialog">
<div class="modal-content " style="height:auto">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title"> Add Category </h4>
<button #click="clearData" type="button" class="close" data-dismiss="modal"><i class="fas fa-times"></i></button>
</div>
<!-- Modal body -->
<div class="modal-body">
<div class="form-group">
<div class="col-lg-12">
<input type="text" class="form-control" id="category_description" name="category_description" v-model="category_description" placeholder="Enter Description">
<p v-if="errors.length">
<span v-for="error in errors"> {{ error }} </span>
</p>
</div>
</div>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="submit"#click="category_description !== undefined ? addCategory : ''" class="btn btn-primary"> Add Category </button>
</div>
</div>
</div>
</div>
</form>
The easiest way to stop this is adding data check. And condition check at top of your method.category_description !== undefined. Btw, move your e.preventDefault() to top too.
First of all do this:
- <button type="submit" #click="category_description !== undefined ? addCategory : ''" class="btn btn-primary"> Add Category </button>
+ <button type="submit" #click.prevent="addCategory" class="btn btn-primary"> Add Category </button>
and then in addCategory:
addCategory() {
if (!this.category_description) {
return;
} else {
// do your stuff here
}
}
When you are clicking on Add Category button, it is triggering the addCategory along with your validation method.
The return value of validation method has no impact on triggering of addCategory.
This issue can be handled in following ways.
Call addCategory only when there is some valid data
<button type="submit" #click="category_description != undefined ? addCategory() : ''" class="btn btn-primary"> Add Category </button>
Call the validation method inside addCategory and then proceed.

Form with radio buttons not submitted

I have a form with two radio buttons which is enabled only when a checkbox is checked.
My problem is when I check the checkbox and click the submit button, the radio value is not getting posted. But after I click on the checkbox and then click on one of the radio buttons then the value is posted.
How to fix this issue?
This is the code I have tried:
HTML
<form [formGroup]="filterProductTargetForm" (ngSubmit)="onSubmitFilterDataList(filterProductTargetForm.value)">
<div class="row">
<div class="col-md-10">
<input type="checkbox" [ngModel]="isProductTypeChecked" formControlName="checkProductType" (change)="onProductTypeChange($event)" />
<label>Select A or B</label>
</div>
</div>
<div class="row">
<label class="col-md-2 uni-label"></label>
<div class="col-md-10 prduct-type-radio">
<fieldset [disabled]="!isProductTypeChecked">
<input type="radio" [checked]="isProductTypeChecked == true" value="A" formControlName="productTypeSelected" [(ngModel)]="productTypeSelected">
<span>B</span>
<br>
<input type="radio" value="B" formControlName="productTypeSelected" [(ngModel)]="productTypeSelected">
<span>B</span>
</fieldset>
</div>
</div>
<button class="uni-button def" [disabled]="!filterProductTargetForm.valid">OK</button>
</form>
TS
ngOnInit() {
this.filterProductTargetForm = this.formBuilder.group({
'checkProductType': '',
'productTypeSelected': ''
});
}
public filterProductTargetForm: FormGroup;
public isProductTypeChecked = false;
onProductTypeChange(event: any) {
this.isProductTypeChecked = !this.isProductTypeChecked;
if(!this.isProductTypeChecked)
this.filterProductTargetForm.controls['productTypeSelected'].reset();
}
First remove all ngModel from your template when using reactive forms.
When the checkbox value changes, in your onProductTypeChange function set the productTypeSelected value
this.filterProductTargetForm.controls['productTypeSelected'].setValue('A');
Working StackBlitz DEMO