Data from array not appear? - vue.js

I am trying to fetch data from the database and display it in Home.vue file,
when go to Vue tab in browser (Hotels:Array[0])
file: Home.vue
<template>
<div class="home">
<form>
<div class="inputcontainer">
<input
class="searchc"
type="text"
v-model="searchcity"
placeholder="Search by city..."
/>
</div>
<div class="wrapper">
<div class="card" v-for="htl in searchcityfunc" :key="htl.id">
<img :src="htl.img" alt="Hotel Image" style="width:100%" />
<h1 class="name">{{ htl.name }}</h1>
<p class="price">{{ htl.price }}</p>
<p class="city">{{ htl.city }}</p>
<p class="button"><button>Reed more</button></p>
</div>
</div>
</form>
</div>
</template>
<script>
// # is an alias to /src
import axios from "axios";
var Hotels = [];
export default {
name: "Home",
data() {
return {
searchcity: "",
Hotels,
};
},
methods:{
fetchAllData: function(){
axios.post('http://localhost//web//action.php',{
action:'fetchall',
}).then(function(response){
Hotels = response.data;
console.log(Hotels);
})
},
searchcityfunc() {
return Hotels.filter((srh) =>
this.searchcity != "" ? !srh.city.indexOf(this.searchcity) : ""
);
},
},
created:function(){
this.fetchAllData();
}
,
};
</script>
From my PHP file, I connected to the database and fetched all the records and encoded them
file: action.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$DBname = "HotelsDB";
$connection = new mysqli($servername,$username,$password,$DBname);
$received_data = json_decode(file_get_contents("php://input"));
$data = array();
if($received_data->action == 'fetchall'){
$sql = "SELECT * FROM Hotels";
$statement = $connection->prepare($sql);
$statement->execute();
$result = $statement->get_result();
while($row = $result->fetch_assoc()){
$data[] = $row;
}
echo json_encode($data);
}
?>
and when trying to search by city nothing appears and Hotels array is (0).

Related

VueJs Internal Server Error 500 when direct access url

I have created one login page using VuejS and when I'm accessing directly into the browser in server it gives me 500 error. but when i click from my website it works.
My Login.vue :
<template>
<div>
<div v-if="progress" class="progress-bg">
<div class="lds-ellipsis"><div></div><div></div><div></div><div></div></div>
</div>
<section class="container login">
<h1 class="login-title text-center">Login With Email</h1>
<form>
<p v-if="error">{{error}}</p>
<div class="form-group">
<input type="text" v-on:keyup="validate()" v-model="email" :disabled="disabled" class="edt-text" name="email" placeholder="Email">
<p v-if="emailError">{{ emailError}}</p>
</div>
<div class="form-group">
<input type="password" v-on:keyup="validate()" v-model="password" :disabled="disabled" class="edt-text" name="password" placeholder="Password">
<p v-if="passwordError">{{ passwordError}}</p>
</div>
<p class="label-forgot-password">Forgot Password?</p>
<div class="form-group">
<button type="button" :disabled="disabled" v-on:click="login" class="btn-login">Login</button>
</div>
</form>
<p class="text-center">Or Connect With</p>
<div class="row social-login-buttons text-center">
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">
<button type="button" class="btn-google"><i class="fa fa-google"></i>Google</button>
</div>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">
<button type="button" class="btn-facebook"><i class="fa fa-facebook"></i>Facebook</button>
</div>
</div>
<div class="row">
<p class="text-center yellow-text margin-20">Don't you have an account?</p>
</div>
</section>
</div>
</template>
<script>
import axios from 'axios'
export default {
name:"Login",
data() {
return {
email:'',
password:'',
progress:false,
disabled:false,
emailError:null,
passwordError:null,
error:null,
}
},
methods: {
async login() {
this.error = ''
if (this.email && this.password && this.validEmail(this.email)) {
this.progress = true
this.disabled = true
let result = await axios.get(
`https://example.com/login/direct?email=${this.email}&password=${this.password}`
)
this.progress=false
this.disabled=false
if(result.status == "200"){
if(result.data['status'] == true) {
localStorage.setItem("user-token", JSON.stringify(result.data['token']))
this.$router.push({name:'Home'})
}
else {
this.error = "Invalid email address / password"
this.email=''
this.password=''
}
}
}
else {
this.validate()
}
},
validate() {
if (!this.email) {
this.emailError = 'Email address required.';
}
else if (!this.validEmail(this.email)) {
this.emailError = 'Enter valid email address.';
}
else{
this.emailError = null;
}
if (!this.password) {
this.passwordError = 'Password is required';
}
else{
this.passwordError = null;
}
},
validEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#"]+(\.[^<>()[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
},
}
};
</script>
My router/index.js :
import Vue from 'vue'
import VueRouter from 'vue-router'';
import ChatList from '../views/Chat/ChatList.vue'
import Chat from '../views/Chat/Chat.vue'
import Login from '../views/Login/Login.vue'
Vue.use(VueRouter)
const routes = [
{
path: '/inbox',
name: 'ChatList',
component:ChatList
},
{
path: '/chat',
name: 'Chat',
component:Chat
},
{
path: '/login',
name: 'Login',
component:Login
},
]
const router = new VueRouter({
mode:'history',
routes
})
export default router
I'm able to access my login page when i click from my site which is linked via hyper link but when i directly hit the url into browser address bar it gives me Internal server error.

How to use "this" in Vue 3

I'm working on a component in Vue3/TypeScript. I'm relatively new to Vue.
I'm dynamically creating a div. I want to be able to delete it when a user clicks on the "x" button. This is the "closeStatus" method.
In JavaScript I can pass this, but Vue hates it.
If anyone can help.
Thanks.
Here is the code:
<template>
<div>
<button #click="addStatus()" >Add Status</button>
<div id="slide" class="slide-modal">
<div class="clear-notifications" #click='clearAllNotifications()'>Clear all notifications</div>
<div class="status-div">
<div>11:00 Booking requested</div>
<div #click="closeStatus(this)"><img src="../assets/cross.svg" /></div>
</div>
<div class="status-div">
<div>11:30 Booking requested</div>
<div #click="closeStatus(this)"><img src="../assets/cross.svg" /></div>
</div>
</div>
</div>
</template>
<script lang="ts">
export default {
name: 'SlideModal',
methods: {
clearAllNotifications() {
const allNotifications = document.querySelectorAll(".status-div");
for(let x=0;x<allNotifications.length;x++) {
allNotifications[x].remove(); //removes all the child elements.
}
document.getElementById('slide').style.visibility='hidden'; //This should be Vue reactive.
},
addStatus() {
document.getElementById('slide').style.visibility='visible'; //This should be Vue reactive.
const statusMessage = "Another Message"
var div = document.createElement('div');
div.setAttribute('class', 'status-div');
div.innerHTML = '<div>' + statusMessage + '</div><div onclick="closeStatus(this)"><img src="/src/assets/cross.svg" /></div>'
document.getElementById('slide').appendChild(div);
},
closeStatus(elm: any) {
elm.parentNode.remove();
const allNotifications = document.querySelectorAll(".status-div");
if(allNotifications.length == 0 ) {
document.getElementById('slide').style.visibility='hidden'; //This should be Vue reactive.
}
}
}
}
</script>
Code is javascript DOM management stuff and far from Vue style.
Vue manages DOM with variables and that is what makes javascript frameworks awesome.
Let me first share the modified code.
<template>
<div>
<button #click="addStatus()" >Add Status</button>
<div id="slide" class="slide-modal" v-show="visibleSlide">
<div class="clear-notifications" #click='clearAllNotifications()'>Clear all notifications</div>
<div class="status-div">
<div>11:00 Booking requested</div>
<div #click="closeStatus(this)"><img src="../assets/cross.svg" /></div>
</div>
<div class="status-div">
<div>11:30 Booking requested</div>
<div #click="closeStatus(this)"><img src="../assets/cross.svg" /></div>
</div>
</div>
</div>
</template>
<script lang="ts">
export default {
name: 'SlideModal',
data() {
return {
visibleSlide: true
}
},
methods: {
clearAllNotifications() {
const allNotifications = document.querySelectorAll(".status-div");
for(let x = 0; x < allNotifications.length; x++) {
allNotifications[x].remove(); //removes all the child elements.
}
this.visibleSlide = false
},
addStatus() {
this.visibleSlide = true;
const statusMessage = "Another Message";
var div = document.createElement('div');
div.setAttribute('class', 'status-div');
div.innerHTML = '<div>' + statusMessage + '</div><div onclick="closeStatus(this)"><img src="/src/assets/cross.svg" /></div>'
document.getElementById('slide').appendChild(div);
},
closeStatus(elm: any) {
elm.parentNode.remove();
const allNotifications = document.querySelectorAll(".status-div");
if(allNotifications.length == 0 ) {
this.visibleSlide = false
}
}
}
}
</script>
I have just updated what is commented: "//This should be Vue reactive."
But it is still not benefiting from Vue framework.
Here is my whole idea of Vue code
<template>
<div>
<button #click="addStatus()" >Add Status</button>
<div id="slide" class="slide-modal" v-if="statuses.length">
<div class="clear-notifications" #click='clearAllNotifications()'>Clear all notifications</div>
<div v-for="status in statuses" :key="status.id" class="status-div">
<div>{{ status.text }}</div>
<div #click="closeStatus(status)"><img src="../assets/cross.svg" /></div>
</div>
</div>
</div>
</template>
<script lang="ts">
export default {
name: 'SlideModal',
data() {
return {
statuses: [
{
id: 1,
text: '11:00 Booking requested'
}, {
id: 2,
text: '11:30 Booking requested'
}
]
}
},
methods: {
clearAllNotifications() {
this.statuses = []
},
addStatus() {
const statusMessage = "Another Message";
this.statuses.push({
id: this.statuses.length + 1,
text: statusMessage
})
},
closeStatus(elm: any) {
const index = this.statuses.map((status) => status.id).indexOf(elm.id);
this.statuses.splice(index, 1);
}
}
}
</script>
As you can see, DOM elements are managed by variables and their operations instead of DOM management methods.
Hope this is helpful

Select checkbox and shows its related objects in Vue.js

In my Vue.js project, I have two separate components are Country and States. I have merged them in one page. So now if I select one country it will display related states. How to do this?
<template>
<div>
<div style=margin-left:355px><country-index></country-index></div>
<div style=margin-left:710px><state-index></state-index></div>
</div>
</template>
<script>
import { ROAST_CONFIG } from '../../../config/config.js';
import CountryIndex from './components/country/Index';
import StateIndex from './components/state/Index';
import { listen } from '../../../util/history.js';
import axios from 'axios'
let baseUrl = ROAST_CONFIG.API_URL;
export default {
name: 'LocationsView',
layout: 'admin/layouts/default/defaultLayout',
middleware: 'auth',
components: {
'country-index' : CountryIndex,
'state-index' : StateIndex,
},
data() {
return { currentComponent:'','countryId':''}
},
methods: {
updateCurrentComponent(){
console.log(this.$route.name);
let vm = this;
let route = vm.$route;
if(this.$route.name == "Locations"){
this.currentComponent = "country-index";
}
}
},
mounted() {
let vm = this;
let route = this.$route;
window.addEventListener('popstate',this.updateCurrentComponent);
},
created() {
this.updateCurrentComponent();
}
}
Country Component
<template>
<div style="display:flex;height:100%">
<d-dotloader v-if="componentLoading" />
<div id="parent" class="list-manager" v-if="!componentLoading">
<div class="list-header">
<div class="bulk-action" :class="{'hide': showTop}" >
<div class="pull-left">
Countries
</div>
<!-- /pull-left -->
<div class="pull-right">
<d-button #click.native = "addCountry();"><i class="icon icon-sm"></i><span>New</span></i></d-button>
</div>
</div>
<!-- /bulk-action -->
<div class="bulk-action" :style ="{display:(showTop)?'block!important':'none!important'}" >
<div class="btn-toolbar">
<d-check field-class="check" v-model="selectAll" wrapper-class="field-check field-check-inline" label-position="right" label="" value="sel" #click.native = "toggleSelectAll();"/>
<d-button :is-loading="isLoading" #click.native = "deleteCountry();">Delete<i class="icon icon-sm" name="trash-2"></i></d-button>
<!-- <div class="pull-right mt5"><div class="green-bubble"></div>{{SelectedItems}}</div> -->
<d-button #click.native = "closeBulkToolBar();">close<i class="icon icon-sm" name="x"></i></d-button>
</div>
</div>
<!-- /bulk-action -->
</div>
<d-dotloader v-if="subListComponentLoading" />
<d-list-items :data="fetchData" #rowClick="changeCountryView" ref="itemsTable">
<d-list-cell column-class="list-item-check" :column-styles="{width: '40px'}" type="selectAll">
<template scope="row">
<div class="field-check field-check-inline" #click.stop="toggleSelect(row.rowIndex)" >
<input type="checkbox" class="check" :id="row.id" :value="row.id" :checked="row.selectAll">
<label></label>
</div>
<d-button #click.native = "editCountry(row.id);">Edit</d-button>
</template>
</d-list-cell>
<d-list-cell column-class="list-item-content">
<template scope="row">
<div class="list-item-content">
<div class="list-item-title">
<div class="pull-right">{{row.ISO_Code}}</div>
<div title="" class="pull-left">{{row.country_name}}</div>
</div>
<div class="list-item-meta">
<div class="pull-right">{{row.Default_Currency}} | {{row.Call_prefix}} </div>
<div class="pull-left">{{row.Zone}}</div>
</div>
<span class="list-item-status enabled"></span>
</div>
</template>
</d-list-cell >
</d-list-items>
</div>
</div>
</template>
<script>
import axios from 'axios'
import { ROAST_CONFIG } from '../../../../../config/config.js';
var baseUrl = ROAST_CONFIG.API_URL;
export default {
data () {
return {
SelectedItems:"",
isLoading:false,
show:true,
searchBy: '',
activeSearch: '',
showTop: false,
selectAll : false,
componentLoading:true,
subListComponentLoading:false,
showModal: false,
form :{
country_name: '',
isCountryEnabled: true,
}
}
},
methods: {
async fetchData ({search, page, filter, sort,rows}) {
let resData;
let vm = this;
axios.defaults.headers.common['Authorization'] = "Bearer "+localStorage.getItem('token');
const res = await axios.post(baseUrl+'/country/fetch',{search, page, filter, sort,rows})
.then((response) => {
if( (typeof(response) != 'undefined') && (typeof(response.data) != 'undefined') && (typeof(response.data.fetch) != 'undefined')){
return response.data.fetch;
}
});
return res;
},
toggleSelect(rowId){
if(typeof(this.$refs.itemsTable.rows[rowId]) != 'undefined'){
this.$refs.itemsTable.rows[rowId].selectAll = !this.$refs.itemsTable.rows[rowId].selectAll;
let data = this.$refs.itemsTable.rows;
let status = false;
let selectAllStatus = true;
let items = 0;
for(var i=0;i <= data.length;i++){
if((typeof(data[i])!= 'undefined')&&(data[i].selectAll)){
items++;
this.SelectedItems = items +" Selected Items";
status = true;
}
if((typeof(data[i])!= 'undefined')&&(!data[i].selectAll)){
selectAllStatus = false;
}
this.showTop = status
}
}
},
toggleSelectAll(){
this.selectAll = !this.selectAll;
let items = 0;
let data = this.$refs.itemsTable.rows;
let status = false;
let rowId = '1'
for(var i=0;i <= data.length;i++){
if((typeof(data[i])!= 'undefined')){
items++;
this.SelectedItems = items +" Selected Items";
status = this.selectAll;
data[i].selectAll = status;
}
}
this.showTop = status
},
closeBulkToolBar(){
this.SelectedItems = "";
this.showTop = false;
},
}
}
State Component
<template>
<div style="display:flex;height:100%">
<d-dotloader v-if="componentLoading" />
<div id="parent" class="list-manager" v-if="!componentLoading">
<div class="list-header">
<div class="bulk-action" :class="{'hide': showTop}" >
<div class="pull-left">
States
</div>
<!-- /pull-left -->
<div class="pull-right">
<d-button #click.native = "addState();"><i class="icon icon-sm"></i><span>New</span></i></d-button>
</div>
</div>
<!-- /bulk-action -->
<div class="bulk-action" :style ="{display:(showTop)?'block!important':'none!important'}" >
<div class="btn-toolbar">
<d-check field-class="check" v-model="selectAll" wrapper-class="field-check field-check-inline" label-position="right" label="" value="sel" #click.native = "toggleSelectAll();"/>
<d-button :is-loading="isLoading" #click.native = "deleteState();">Delete<i class="icon icon-sm" name="trash-2"></i></d-button>
<!-- <div class="pull-right mt5"><div class="green-bubble"></div>{{SelectedItems}}</div> -->
<d-button #click.native = "closeBulkToolBar();">close<i class="icon icon-sm" name="x"></i></d-button>
</div>
</div>
<!-- /bulk-action -->
</div>
<d-dotloader v-if="subListComponentLoading" />
<d-list-items :data="fetchData" #rowClick="changeStateView" ref="itemsTable">
<d-list-cell column-class="list-item-check" :column-styles="{width: '40px'}" type="selectAll">
<template scope="row">
<div class="field-check field-check-inline" #click.stop="toggleSelect(row.rowIndex)" >
<input type="checkbox" class="check" :id="row.id" :value="row.id" :checked="row.selectAll">
<label></label>
</div>
<d-button #click.native = "editState(row.id);">Edit</d-button>
</template>
</d-list-cell>
<d-list-cell column-class="list-item-content">
<template scope="row">
<div class="list-item-content">
<div class="list-item-title">
<div class="pull-right">{{row.ISO_Code}}</div>
<div title="" class="pull-left">{{row.state_name}}</div>
</div>
<div class="list-item-meta">
<div class="pull-left">{{row.country_name}} </div>
<div class="pull-right">{{row.Zone}}</div>
</div>
<span class="list-item-status enabled"></span>
</div>
</template>
</d-list-cell >
</d-list-items>
</div>
<state-add></state-add>
<state-edit></state-edit>
</div>
</template>
<script>
import axios from 'axios'
import { ROAST_CONFIG } from '../../../../../config/config.js';
var baseUrl = ROAST_CONFIG.API_URL;
export default {
data () {
return {
SelectedItems:"",
isLoading:false,
show:true,
searchBy: '',
activeSearch: '',
showTop: false,
selectAll : false,
componentLoading:true,
subListComponentLoading:false,
showModal: false,
form :{
country_name: '',
isCountryEnabled: true,
}
}
},
methods: {
async fetchData ({search, page, filter, sort,rows}) {
let resData;
let vm = this;
axios.defaults.headers.common['Authorization'] = "Bearer "+localStorage.getItem('token');
const res = await axios.post(baseUrl+'/state/fetch',{search, page, filter, sort,rows})
.then((response) => {
if( (typeof(response) != 'undefined') && (typeof(response.data) != 'undefined') && (typeof(response.data.fetch) != 'undefined')){
return response.data.fetch;
}
});
return res;
},
changeStateView(row){
if(typeof(this.$children[7]) != 'undefined'){
this.$parent.stateId = row.id;
this.viewComponent = "state-main";
this.$children[7].readState(this.$parent.stateId);
this.$router.push({name:"StatesView", params: {id:row.id}});
}
},
toggleSelect(rowId){
if(typeof(this.$refs.itemsTable.rows[rowId]) != 'undefined'){
this.$refs.itemsTable.rows[rowId].selectAll = !this.$refs.itemsTable.rows[rowId].selectAll;
let data = this.$refs.itemsTable.rows;
let status = false;
let selectAllStatus = true;
let items = 0;
for(var i=0;i <= data.length;i++){
if((typeof(data[i])!= 'undefined')&&(data[i].selectAll)){
items++;
this.SelectedItems = items +" Selected Items";
status = true;
}
if((typeof(data[i])!= 'undefined')&&(!data[i].selectAll)){
selectAllStatus = false;
}
this.showTop = status
}
}
},
toggleSelectAll(){
this.selectAll = !this.selectAll;
let items = 0;
let data = this.$refs.itemsTable.rows;
let status = false;
let rowId = '1'
for(var i=0;i <= data.length;i++){
if((typeof(data[i])!= 'undefined')){
items++;
this.SelectedItems = items +" Selected Items";
status = this.selectAll;
data[i].selectAll = status;
}
}
this.showTop = status
},
closeBulkToolBar(){
this.SelectedItems = "";
this.showTop = false;
},
}
}
Without your component codes it will be difficult to accuratly answer but I can give a try. To communicate between your two components that don't have parent/child relationship you can use an EventBus. You have several choices on how to set up your EventBus; you can pass your event through your Vue root instance using $root, or you can create a dedicated Vue component like in this example.
Considering that you already have binded the event countrySelected($event) on each of your country checkbox, you could achieve to display the related states using something like this:
./components/country/Index
The CountryIndex trigger an event while a country is selected
methods: {
countrySelected(event) {
let currentTarget = event.currentTarget
this.$root.$emit("display-states",currentTarget.countryId);
}
}
./components/state/Index
The stateIndex component listen to the event and display the related state
mounted() {
/**
* Event listener
*/
this.$root.$on("display-states", countryId => {
this.diplayStates(countryId);
});
},
methods: {
displayStates(countryId) {
//your method selecting the states to be diplayed
}

How can I pass input file with vue.js 2?

My vue component like this :
<template>
<div class="modal" tabindex="-1" role="dialog">
...
<div class="form-group">
<label for="change-image">Change image</label>
<input type="file" name="replace" v-on:change="changeImage">
</div>
<div class="form-group">
<label for="alt-image">Alt attr</label>
<input type="text" class="form-control" v-model="altImage">
</div>
<div class="checkbox">
<label>
<input type="checkbox" v-model="mainCover"> Set Cover
</label>
</div>
<button type="button" class="btn btn-success" #click="editImageProduct">
Edit
</button>
...
</div>
</template>
<script>
export default{
...
data() { return {altImage: '', mainCover: '', imageChanged: '', image: ''}},
methods: {
editImageProduct(event) {
const payload = {alt_image: this.altImage, main_cover: this.mainCover, image_changed: this.imageChanged}
this.$store.dispatch('editImageProduct', payload)
},
changeImage(e) {
var files = e.target.files || e.dataTransfer.files
if (!files.length)
return;
this.createImage(files[0])
this.imageChanged = files[0]
},
createImage(file) {
var image = new Image()
var reader = new FileReader()
var vm = this
reader.onload = (e) => {
vm.image = e.target.result
};
reader.readAsDataURL(file)
},
}
}
</script>
I want to send the parameters to controller. It will go through modules, api, routes and controller
On the controller, I do like this :
public function editImage(Request $request)
{
dd($request->all());
}
When executed, the result like this :
array:5 [
"alt_image" => "test alt"
"main_cover" => true
"image_changed" => []
]
The param image_changed is empty
Whereas on the component, I do console.log, it display the result
When I do console.log(files[0]), the result like this :
How can I solve this problem?

Update method didn't post anything to controller angular2

I am trying to make a basic crud app for comments in angular2 but I am having a bizarre issue that I cant figure out.
Whenever I try to update the data I get 500 internal server error which says the the parameters I am sending to my controller method are null. Although I used same method for POST but the update method doesn't send data to controller while POST does. Help me out in this please!
Comments.component.html
<p-growl [value]="msgs"></p-growl>
<div class="container" *ngIf="showMaster">
<form [formGroup]="userform" (ngSubmit)="onSubmit(userform.value)">
<p-panel header="Validate">
<div class="ui-grid ui-grid-responsive ui-grid-pad ui-fluid" style="margin: 10px 0px">
<div class="ui-grid-row">
<div class="ui-grid-col-2">
Comment Code *:
</div>
<div class="ui-grid-col-6">
<p-inputMask formControlName="commcode" mask="99/9999" #commcode
placeholder="Required" [(ngModel)]="comment.CommCode"></p-inputMask>
</div>
<div class="ui-grid-col-4">
<div class="ui-message ui-messages-error ui-corner-all"
*ngIf="!userform.controls['commcode'].valid&&userform.controls['commcode'].dirty">
<i class="fa fa-close"></i>
Comment Code is required
</div>
</div>
</div>
<div class="ui-grid-row">
<div class="ui-grid-col-2">
Person Name *:
</div>
<div class="ui-grid-col-6">
<input pInputText type="text" formControlName="persname" placeholder="Required" [(ngModel)]="comment.PersName"/>
</div>
<div class="ui-grid-col-4">
<div class="ui-message ui-messages-error ui-corner-all"
*ngIf="!userform.controls['persname'].valid&&userform.controls['persname'].dirty">
<i class="fa fa-close"></i>
Person Name is required
</div>
</div>
</div>
<div class="ui-grid-row">
<div class="ui-grid-col-2">
Company Name *:
</div>
<div class="ui-grid-col-6">
<input pInputText type="text" formControlName="compname" placeholder="Required" [(ngModel)]="comment.CompanyName"/>
</div>
<div class="ui-grid-col-4">
<div class="ui-message ui-messages-error ui-corner-all" *ngIf="!userform.controls['compname'].valid&&userform.controls['compname'].dirty">
<i class="fa fa-close"></i>
Company Name is required
</div>
</div>
</div>
<div class="ui-grid-row">
<div class="ui-grid-col-2">
Branch :
</div>
<div class="ui-grid-col-6">
<input pInputText type="text" formControlName="branch" placeholder="Required" [(ngModel)]="comment.BranchName"/>
</div>
<div class="ui-grid-col-4">
<div class="ui-message ui-messages-error ui-corner-all" *ngIf="!userform.controls['branch'].valid&&userform.controls['branch'].dirty">
<i class="fa fa-close"></i>
<span *ngIf="userform.controls['password'].errors['required']">Branch Name is required</span>
</div>
</div>
</div>
<div class="ui-grid-row">
<div class="ui-grid-col-2">
Comments:
</div>
<div class="ui-grid-col-6">
<textarea pInputTextarea type="text" formControlName="comment" [(ngModel)]="comment.Comment"></textarea>
</div>
<div class="ui-grid-col-4"></div>
</div>
<div class="ui-grid-row">
<div class="ui-grid-col-2"></div>
<div class="ui-grid-col-6">
<button pButton type="submit" label="Submit" [disabled]="!userform.valid" *ngIf="newComment"></button>
</div>
<div class="ui-grid-col-4"></div>
</div>
<div class="ui-grid-row" *ngIf="updateComment">
<div class="ui-grid-col-2"></div>
<div class="ui-grid-col-6">
<button pButton type="submit" label="Update" [disabled]="!userform.valid" *ngIf="updateComment"></button>
</div>
<div class="ui-grid-col-6">
<button pButton type="submit" label="Delete" [disabled]="!userform.valid" *ngIf="updateComment"></button>
</div>
<div class="ui-grid-col-4"></div>
</div>
</div>
</p-panel>
</form>
Comments
Comments.component.ts
import {Component, OnInit} from '#angular/core';
import {Message} from '../message';
import {Validators, FormControl, FormGroup, FormBuilder} from '#angular/forms';
import {Comment} from './comment';
import {AppService} from '../app.service';
#Component({
selector: 'commments',
templateUrl: '/app/comments/comment.component.html'
})
export class CommentsComponent implements OnInit {
comments: Comment[];
selectedComment: Comment[];
comment: Comment = new PrimeComment();
newComment: boolean;
msgs: Message[] = [];
userform: FormGroup;
showMaster: boolean;
updateComment: boolean;
disadd: boolean;
constructor(private fb: FormBuilder, private _appService: AppService) { }
divComment() {
this.showMaster = true;
this.newComment = true;
this.updateComment = false;
this.comment.CommCode = '';
this.comment.PersName = '';
this.comment.BranchName = '';
this.comment.Comment = '';
this.comment.CompanyName = '';
}
getComments() {
this._appService.getComments().subscribe(
res => this.comments = res
);
}
ngOnInit() {
this.userform = this.fb.group({
'commcode': new FormControl('', Validators.required),
'persname': new FormControl('', Validators.required),
'compname': new FormControl('', Validators.required),
'branch': new FormControl('', Validators.required),
'comment': new FormControl('', Validators.required),
});
this.getComments();
}
onSubmit(value: string) {
this.msgs = [];
this.msgs.push({ severity: 'info', summary: 'Success', detail: 'Form Submitted' });
this.showMaster = false;
this.disadd = false;
if (this.newComment) {
this._appService.postComments(this.comment).subscribe(
res => this.comments = res
);
}
else {
this._appService.updateComments(this.comment).subscribe(
res => this.comments = res
);
}
}
onRowSelect(event) {
this.disadd = true;
this.showMaster = true;
this.newComment = false;
this.updateComment = true;
this.comment = this.cloneComment(event.data);
}
cloneComment(c: Comment): Comment {
let comment = new PrimeComment();
for (let prop in c) {
comment[prop] = c[prop];
}
return comment;
}
//get diagnostic() {
// //return JSON.stringify(this.userform.value);
//}
}
class PrimeComment implements Comment {
constructor(public CommCode?, public PersName?, public CompanyName?, public BranchName?, public Comment?) { }
}
App.service.ts
import {Injectable} from '#angular/core';
import {Http, Headers, Response} from '#angular/http';
import {Comment} from './comments/comment';
#Injectable()
export class AppService {
constructor(private _http: Http) { }
getComments() {
return this._http.get('Comments/GetComments').map(res => res.json());
}
postComments(c: Comment) {
var json = JSON.stringify(c);
var header = new Headers();
header.append('Content-Type', 'application/json');
return this._http.post('Comments/PostComments', json, { headers: header }).map(res => res.json());
}
updateComments(cd: Comment) {
var json1 = JSON.stringify({ cd });
var header = new Headers();
header.append('Content-Type', 'application/json');
return this._http.post('Comments/UpdateComments', json1, { headers: header }).map(res => res.json());
}
delComments(commcode: Comment) {
var json = JSON.stringify(commcode);
var header = new Headers();
header.append('Content-Type', 'application/json');
return this._http.post('Comments/DeleteComments', json, { headers: header }).map(res => res.json());
}
}
First thing no need to use formControl & [(ngModel)] together.
//access your form like this
userform: FormGroup;
constructor(fb: FormBuilder) {
this.userform = fb.group({
commcode: '',
persname: '',
....
});
}
onSubmit(){
console.log(this.userform.value);
//update your post params
}