Data binding in angular 2 - angular2-template

I have 2 input boxes in my HTML file.
<div class="row">
<label>Input1</label>
<input type="text" name="input1" [(ngModel)]="model.valueInput1">
</div>
<div class="row">
<label>Input2</label>
<input type="text" name="input2" [(ngModel)]="model.valueInput2">
</div>
And my model is:
model = {
valueInput1:string = "",
valueInput2:string = ""
}
Now I want, when I bind 'input1', the value should bind with 'input2' automatic. But if I change 'input2' value, it should not make changes in 'input1'.
How can I achieve this kind of binding in Angular 2?

<div class="row">
<label>Input1</label>
<input type="text" name="input1" [(ngModel)]="model.valueInput1" (ngModelChange)="updateInput($event)">
</div>
..........
In the ts
updateInput(value: string): void {
this.model.valueInput2 = value;
}
that's it

Related

Laravel 8: Input mask not properly working in livewire

In the application, we used the input mask of jquery in one of the module.
In that module, there's a tab. whenever I tried to change the tab or submit it.
The value of tin is always null
Blade file
<div wire:ignore.self class="tab-pane active" class="tab-pane " id="vendor-customer-tab" role="tabpanel">
<div class="mb-3 row">
<label for="bank-account-number" class="col-md-3 col-form-label">TIN<span class="required">*</span></label>
<div class="col-md-9">
<!-- <input class="form-control tin-mask" type='text' id="tin_num" placeholder="Enter TIN Number" > -->
<input class="form-control tin-mask" type='text' id="tin_num" placeholder="Enter TIN Number" wire:model.defer="tin">
<!-- <input type="hidden" name="tin_num" wire:model.defer="tin"/> -->
#error('tin')
<span class="text-danger">
{{$message}}
</span>
#enderror
</div>
</div>
</div>
Script
<script type="text/javascript">
$(document).ready(function(){
$('.tin-mask').inputmask("999-999-999-999");
$(".tin-mask").val("000-000-000-000");
// $('#tin_num').change(function(e){
// var tin_number = $('#tin_num').val();
// $("input[name='tin_num']").val(tin_number);
// e.preventDefault();
// return false;
// });
// $(".tin-mask").attr("value", "000-000-000-000");
});
</script>
Question: Why everytime I tried to change the tab or submit, the value of TIN becomes blanks.?
Probably because
wire:model.defer="tin"
and
$(".tin-mask").val("000-000-000-000");
don't go hand-in-hand. jQuery sets the value, but wire:model also sets the value and so far $tin probably has no value.

Insert ForEach Value in View into the Database MVC

Hi currently I am doing a shopping cart for my project
I would like to ask how can I import the values in a ForEach to the database.
For example, I have the following data in my view.
#foreach (Cart_Has_Services c in Model)
{
<div class="cart-row">
<div class="cart-items">#c.Cart_Service</div>
<div class="cart-items">#c.Additional_Notes</div>
<div class="cart-items">#c.Unit_Price</div>
<div class="cart-items">
<form asp-controller="Cart" asp-action="UpdateCart" formaction="post">
<input type="number" class="item-quantity-input" value="#c.Quantity" />
<input type="submit" class="btn btn-secondary" value="Update" />
</form>
</div>
<div class="cart-items">
<a asp-controller="Cart"
asp-action="DeleteItem"
asp-route-id="#c.Cart_Id"
onclick="return confirm('Delete Serivce #c.Cart_Service')">
Delete
</a>
</div>
</div>
}
As for now, I want to INSERT data (Cart Service, Additional Notes and Quantity) into my database (Order).
In my controller:
public IActionResult Checkout(Cart_Has_Services cart)
{
List<Cart_Has_Services> carts = DBUtl.GetList<Cart_Has_Services>("SELECT * FROM Cart");
string sql = #"INSERT INTO [Order](Order_Name,Order_Description,Order_Quantity)
VALUES('{0}','{1}',{2})";
int ord = DBUtl.ExecSQL(sql, cart.Cart_Service, cart.Additional_Notes, cart.Quantity);
if (ord == 1)
{
TempData["Message"] = "Perofrmance Successfully Created";
TempData["MsgType"] = "success";
return RedirectToAction("Success");
}
else
{
ViewData["Message"] = DBUtl.DB_Message;
ViewData["MsgType"] = "danger";
return View("ShoppingCart");
}
}
I tried the method that I have inserted but it created without inserting the data.
How can I solve this problem?
Hope can get some guidance.
Thank you
The form in the view only submit Quantity, without Cart_Service and Additional_Notes.
To submit their value, you may set hidden inputs in the form. Also you should set name attribute for the input for model binding.
#foreach (Cart_Has_Services c in Model)
{
<div class="cart-row">
<div class="cart-items">#c.Cart_Service</div>
<div class="cart-items">#c.Additional_Notes</div>
<div class="cart-items">#c.Unit_Price</div>
<div class="cart-items">
<form asp-controller="Cart" asp-action="UpdateCart" formaction="post">
<input type="hidden" name="Cart_Service" value="#c.Cart_Service" />
<input type="hidden" name="Additional_Notes" value="#c.Additional_Notes" />
<input type="number" name="Quantity" class="item-quantity-input" value="#c.Quantity" />
<input type="submit" class="btn btn-secondary" value="Update" />
</form>
</div>
<div class="cart-items">
<a asp-controller="Cart"
asp-action="DeleteItem"
asp-route-id="#c.Cart_Id"
onclick="return confirm('Delete Serivce #c.Cart_Service')">
Delete
</a>
</div>
</div>
}

Dynamic input value related to another values

I would like to make the value ****here****of the input id="inputWorkload" dynamic and related to the value of inputDuration (newTask.duration * 2 )
How to do it with Vue js?
<div class="col-sm-2">
<div class="form-group">
<label for="inputDuration">Duration (H)</label>
<input class="form-control" id="inputDuration" min="4" step="4" type="number" v-model="newTask.duration">
</div>
</div>
<div class="col-sm-2">
<div class="form-group">
<label for="inputWorkload">Workload</label>
<input disabled class="form-control" id="inputWorkload" value="****here****">
</div>
</div>
Add an on change event to the duration:
<input class="form-control" id="inputDuration" min="4" step="4" type="number" v-model="newTask.duration" onchange="myFunction()">
Then write some JavaScript which gets the value of the duration on change and updates the workload value based on that.
<script>
function myFunction() {
var inputDurationValue = document.getElementById("inputDuration").value;
document.getElementById("inputWorkload") = inputDurationValue;
}
</script>
With a watcher. Something like this.
data: {
//define your #inputWorkload variable , let's say "workload"
},
watch: {
newTask: {
handler(val){
this.workload = val.duration * 2;
},
deep: true
},
}
// in your template
<input disabled class="form-control" id="inputWorkload" :value="workload">

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

Aurelia custom element access data from child to parent view model

I am new to Aurelia and need help accessing values from custom element in another view.
I have a scenario where I would like to share input file for attachment in multiple forms. One of the approach I am taking is to create custom element for input files that can be shared with multiple forms in web application.
Below is my code:
Custom element called FilePicker which will be shared between multiple forms. In my Request paged I inserted the custom element called:
<file-picker router.bind="router" accept="image/*" multiple="true" ></file-picker>
My requirement is to access property called validFiles which is an array. I would like to use values from validFiles to custom object in Request view model called formData['attachment']
TS:
import { customElement, useView, bindable, bindingMode } from 'aurelia-framework';
#customElement('file-picker')
#useView('./file-picker.html')
export class FilePicker {
#bindable accept = '';
#bindable multiple = false;
#bindable({ defaultBindingMode: bindingMode.twoWay }) files: FileList;
validFiles = [];
input: HTMLInputElement;
// Validate function for on change event to input file.
public filesChanged() {
if (!this.files) {
this.clearSelection();
}
if (this.files) {
this.processFiles();
}
}
// Trigger on button click
public triggerInputClick() {
this.input.click();
}
// Find value in array of object
private findValinArrObj(arr, key, val) {
return arr.map(function (v) { return v[key] }).indexOf(val);
}
// Process file for each new files uploaded via browser
private processFiles() {
if (this.files) {
for (let i = 0; i < this.files.length; i++) {
let findFile = this.findValinArrObj(this.validFiles, 'name', this.files.item(i).name);
if (findFile === -1) {
this.validFiles.push(this.files.item(i));
}
}
this.clearSelection();
}
}
// Remove file from fileNames and validFiles array
public removeByFileName(fileName) {
if (this.validFiles) {
for (let i = 0; i < this.validFiles.length; i++) {
if (this.validFiles[i].name === fileName) {
this.validFiles.splice(i, 1);
}
}
}
}
// Clear input file in DOM
private clearSelection() {
this.input.type = '';
this.input.type = 'file';
}
}
HTML:
<template>
<input type="file" accept.bind="accept" multiple.bind="multiple"
files.bind="files" ref="input"
style="visibility: hidden; width: 0; height: 0;">
<button class="btn btn-primary" click.delegate="triggerInputClick()">
<slot>Browse...</slot>
</button>
<ul class="list-group" if.bind="validFiles">
<li class="list-group-item" repeat.for="file of validFiles" style="padding: 0; border:none;">
${file.name} <span class="glyphicon glyphicon-remove text-danger" style="cursor: pointer;" click.delegate="removeByFileName(file.name)"></span>
</li>
</ul>
</template>
Parent View Model:
TS:
export class Request {
pageTitle: string = "Request Page";
title: string = '';
description: string = '';
businessValue: string = '';
emails: string = '';
formData: object = {};
public postData() {
this.formData['title'] = this.title;
this.formData['description'] = this.description;
this.formData['businessValue'] = this.businessValue;
this.formData['emails'] = this.emails;
this.formData['attachment'] = [];
console.log(this.formData);
}
}
HTML:
<template>
<require from="./request.css"></require>
<require from="../../resources/elements/file-picker"></require>
<div class="panel panel-primary">
<div class="panel-heading">${pageTitle}</div>
<div class="panel-body">
<form class="form-horizontal">
<div class="form-group">
<label for="title" class="col-sm-2 control-label">Title</label>
<div class="col-sm-10">
<input type="text" value.two-way="title" class="form-control" id="title" placeholder="Brief one-line summary of the request">
</div>
</div>
<div class="form-group">
<label for="description" class="col-sm-2 control-label">Description</label>
<div class="col-sm-10">
<input type="text" value.two-way="description" class="form-control" id="description" placeholder="Detailed description of the request">
</div>
</div>
<div class="form-group">
<label for="description" class="col-sm-2 control-label">Business Value</label>
<div class="col-sm-10">
<input type="text" value.two-way="businessValue" class="form-control" id="description" placeholder="Description of how this offers business value">
</div>
</div>
<div class="form-group">
<label for="emails" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input type="text" value.two-way="emails" class="form-control" id="emails" placeholder="Provide email address">
</div>
</div>
<div class="form-group">
<label for="exampleInputFile" class="col-sm-2 control-label">Attachment(s)</label>
<div class="col-sm-10">
<file-picker router.bind="router" accept="image/*" multiple="true" ></file-picker>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<button type="submit" class="btn btn-default pull-right" click.trigger="postData()">Submit</button>
</div>
</div>
</form>
</div>
</div>
</template>
Any help is really appreciated. :)
You can set up two-way-binding on your Request view, to bind the validFiles in your child view (file-picker) to a variable in your parent view (Request):
request.html:
<file-picker valid-files.two-way="validFiles"></file-picker>
request.ts:
public validFiles: File[];
file-picker.ts:
#bindable
public validFiles: File[];
This way any changes made to the validFiles object in either the child or the parent will update the object in both viewmodels.