How to get control type in template driven form in Angular 4 - forms

I have a form in angular 4 component. The fields are generated dynamically, i.e., using ngFor to generate the inputs. The inputs are of different types, e.g. checkbox, text...
In the ts code, how can i know the type of the input control?
HTML
<form *ngIf="active" #easyForm="ngForm" (ngSubmit)="onSubmit()">
<div *ngFor="let i in items">
<input type="text" name="text-{{item.id}}" [(ngModel)]="item.text">
<input type="checkbox" name="checkbox-{{item.id}} (ngModel)]="item.checked">
</div>
</form>
TS
#ViewChild('easyForm') set content(easyForm: NgForm) {
this.easyForm = easyForm;
if (this.easyForm) {
const keys = Object.keys(this.easyForm.controls);
foreach(let key in keys) {
this.easyForm.controls[key] <---- am i able to get the type of the control here?
}
}

Related

meteor - how to code a bootstrap modal template to re-render html input values even if the user has typed in them

I'm using iron router to pass data to a bootstrap modal template. The modal contains a html form including many text inputs. The modal is re-used for 3 different features. I use a Session variable to keep track of which modal type is in use. Type 0 = blank form, type 1 = partial edit, type 2 = full edit. The form itself remains the same visually for all types. The only thing that changes is which input boxes contain a value.
For a type 1 edit only 2 boxes would contain values. For a type 2 edit all boxes would contain values. And the type 0 would be empty boxes.
// routes.js
Router.route('/mypage', function () {
var mtype = Session.get("mtype");
this.layout('myLayout');
this.render('my_popup', {to:'my_popup', data: function() {
switch (mtype) {
case 1:
return {box1:'box 1 text', box2:'box 2 text', box3:''};
case 2:
return {box1:'box 1 text', box2:'box 2 text', box3:'box 3 value'};
default:
return {box1:'', box2:'', box3:''};
}
}});
});
// main.html
<template name="myLayout">
{{> yield "my_popup"}}
</template>
<template name="my_popup">
<div class="modal fade" id="my_popup">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<div class="modal-title label label-primary">Title</div>
</div>
<div class="modal-body">
<form class="js-form-submit" id="my_form" name="my_form">
<div class="form-group">
<input class="form-control" type="text" name="box1" maxlength="64" placeholder="something" value="{{box1}}"/>
</div>
<div class="form-group">
<input class="form-control" type="text" name="box2" maxlength="64" placeholder="something" value="{{box2}}"/>
</div>
<div class="form-group">
<input class="form-control" type="text" name="box3" maxlength="64" placeholder="something" value="{{box3}}"/>
</div>
</form>
</div>
<div class="modal-footer">
<button class="js-form-ok btn btn-success btn-sm">submit</button>
<button class="btn btn-warning btn-sm" data-dismiss="modal">cancel</button>
</div>
</div>
</div>
</div>
</template>
Initially I tried passing an object to the modal template that only contained the properties that would be displayed. That didn't overwrite existing input values so I had to use the same object for each modal type and use empty strings for unused properties. I tried calling the reset() method on the form prior to showing the modal. In that case it caused the entire template to stop re-rendering.
Prior to showing the modal I set the session variable to the type of modal that will be displayed.
Session.set('mtype', 1);
That triggers iron router into sending the proper data to the template, unused properties are cleared and the template successfully re-renders.
Unfortunately if I type in one of the html inputs the template does not reset its value when it's re-rendered. This seems to be related to the same problem I encountered with the reset() method. If the input contains custom text (value is typed) then the modal doesn't display the new data sent to the template when the Session variable is changed. It preserves the user entered text.
What's the best way to re-use a bootstrap modal form in meteor? Should I use a helper instead of iron router to get the data object? Something like...
{{#with getData}}
Why is the user entered text being preserved?
I've also tried using the defaultValue attribute instead of value. The same issue occurs with both attributes.
To test the bug:
open the web console
Session.set('mtype',1);
$('#my_popup').modal('show');
type something in the 3rd text box
click off the modal to hide it
Session.set('mtype',0);
$('#my_popup').modal('show');
You'll see that the value you typed is still visible despite having sent empty strings to each box.
Another way:
Session.set('mtype',2);
$('#my_form')[0].reset();
Session.set('mtype',1);
$('#my_popup').modal('show');
You'll see that none of the boxes contain values despite having sent new strings of text to each box.
The only solution I've found is to use defaultValue in the template and then loop through the form fields before modal is shown and set value = defaultValue.
<input class="form-control" type="text" name="box1" maxlength="64" placeholder="something" defaultValue="{{box1}}"/>
Template.my_popup.rendered = function() {
$("#my_popup").on('show.bs.modal', function() {
var elems = $('#my_form')[0].elements;
for (var i=0; i<elems.length; i++) {
if (elems[i].hasAttribute('defaultValue')) {
elems[i].value = elems[i].getAttribute('defaultValue');
}
}
});
};

How to pass a data like a database data or php constant data to display in a form in main.js

We build a custom bundle follow with this instructor https://blog.sulu.io/how-to-develop-a-bundle-in-the-sulu-admin-1
We need to know how to pass data from a database to render radio input choices or dropdown select.
We try to create an add/edit form and in the form, we have a radio and dropdown we made with hardcore in HTML file in Vendor/TransportationBundle/Resources/public/js/components/transportation/form/form.html
The code is
<div class="grid-row">
<label for="transportation-transportationType"><%= translations.transportationType %></label>
<div class="custom-radio">
<input name="transportationType" id="transportation-transportationType-1" type="radio"
class="form-element content-type" value="1" data-mapper-property="transportationType">
<span class="icon"></span>
</div>
<span class="clickable"><%= translations.private_shuttle %></span>
<div class="custom-radio">
<input name="transportationType" id="transportation-transportationType-2" type="radio"
class="form-element content-type" value="2" data-mapper-property="transportationType">
<span class="icon"></span>
</div>
<span class="clickable"><%= translations.shared_shuttle %></span>
<div class="custom-radio">
<input name="transportationType" id="transportation-transportationType-3" type="radio"
class="form-element content-type" value="3" data-mapper-property="transportationType">
<span class="icon"></span>
</div>
<span class="clickable"><%= translations.airplane %></span>
</div>
Is this have a way to change those radio to fetch the data from an array or a way to fetch the data from some controller action? or Have another way to use twig file with twig feature instead of html file?
Please provide a solution for us? Thank you
Sorry for my English.
You can e.g. check this Controller from the core. You can get data from wherever you want in the controller and pass it to the template:
<?php
class AcmeController {
public function testAction() {
$data = /* Get data somehow */;
return $this->render('template', ['data' => $data]);
}
}
Then you can access the data using the data twig variable in the rendered template.

Correct way to pass different v-model values for same parameter name in POST request

FIDDLE
I am assigning v-model values from a form to parameters in an api. There is only one parameter in the api that I have to assign to both inputs i.e.: name. The name is a required field.
Using v-model values of each input, if the first radiobtn is selected, it will return null for the value of name. If the second radiobtn is selected, the user must enter text into the textbox.
I need to check whether the first radio button has been clicked OR the user entered text in the textbox and successfully pass the value of the first radiobtn or the textbox to the same api parameter (name).
How can I do this?
HTML:
<label class="radiogrp"><input type="radio" v-model="picked" name="default_user" value="reg" >Mary</label>
<label class="radiogrp"><input type="radio" v-model="picked" name="new_usr" value="non-reg"><input type="text" v-model="new_user" ></label>
JS:
/* API parameters
name: (string) or (null)
*/
new Vue({
el: '#app',
data: {
picked: Boolean,
new_user: ""
},
/* Two v-model form values for the one property in the API. */
submit_name(){
this.$http.post("https://jsonplaceholder.typicode.com/users",{
name: this.picked || this.new_user})
// ....then() etc.
}
});
You can add #input event which can update the new_usr field on input changes.
Also you can watch picked variable to make sure if you toggle between radio buttons, new_usr should be reset.
function callMe(){
var vm = new Vue({
el : '#root',
data : {picked : '',new_usr:''},
methods: {
callApi(){
let dataApi={}
if(this.new_usr.length){
dataApi.name=this.new_usr;
}else{
dataApi.name=this.picked;
}
console.log('You selected=', dataApi.name)
}
},
watch:{
picked: function (val) {
this.new_usr='';
}
}
})
}
callMe();
<script src="https://cdn.jsdelivr.net/npm/vue#2.5.11/dist/vue.js"></script>
<div id='root'>
<div>
<label class="radiogrp">
<input type="radio" v-model="picked" name="default_user" value="reg" >Mary</label>
<label class="radiogrp">
<input type="radio" v-model="picked" name="new_usr" value="non-reg">
<input type="text" #input="evt=>new_usr=evt.target.value" :value="new_usr" > </label>
<button #click="callApi">hit me</button>
<span>Picked: {{ new_usr }}</span>
</div>
</div>

On Button Click Validate a template form in Angular 2

I am new to Angular 2.
I have created a simple template which has two text field, I want to required field validate those two fields.
Login Form
<form #loginForm="ngForm" (ngSubmit)="onSubmit(loginForm)" novalidate>
<div class="container">
<div class="form-group">
ooooo <label><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="uname" required [(ngModel)]="UserData.uname" #uname="ngModel">
<div *ngIf="loginForm.invalid" class="alert alert-danger">
<div [hidden]="!uname.errors.required"> Name is required </div>
</div>
</div>
<div class="form-group">
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="pwd" required [(ngModel)]="UserData.pwd" #pwd="ngModel">
<div *ngIf="UserData.pwd.errors && (UserData.pwd.dirty || UserData.pwd.touched)" class="alert alert-danger">
<div [hidden]="!UserData.pwd.errors.required">Password is required </div>
</div>
<button type="submit" >Login</button>
</div>
</div>
</form>
My Component
import { Component } from "#angular/core"
import { User } from "./UserModel"
#Component({
selector: 'my-login',
templateUrl:"app/Login/login.html"
})
export class LoginComponent
{
//alert: any("hello");
UserData: User = new User("", "");
submitted = false;
onSubmit(form: any) {
alert("dfsdfsd" + form);
if (!form.invalid) {
alert(this.UserData.uname);
alert(this.UserData.pwd);
this.submitted = true;
}
}
}
What i want to implement is-
When the form loads no validation message should appear?
When user clicks on the submit button then the required message should appear?
In both the textbox i have applied different type of checks to show the message that is inconsistent? so there should be a consistent way to solve this.
Many thanks for the help.
Maybe make use of the submitted variable, and use that in template, to not show message, until submitted is true, which we set it as in the submit function.
Also you wouldn't really need the two-way-binding here, since the object your form produces is directly assignable to your UserData.
The validation messages I'd just set then simply like this, where we are targeting the username:
<div *ngIf="uname.errors?.required && submitted"> Name is required </div>
in your submit function I'd pass loginForm.value as parameter instead of just loginForm. This way you get the form object ready to be used :)
And in your function you can assign the object to your UserData variable.
onSubmit(form: any) {
this.submitted = true;
this.UserData = form;
}
If you do want to keep the two-way-binding, it's of course totally possible! :)
DEMO

Foundation 5 & Abide: a custom validator for a set of checkboxes?

I would like to create a validator for abide for a set of checkboxes.
Let's consider a set of 5 checkboxes. The user is asked to check 3 max, and at least 1.
So, here is my work-in-progress code:
<div data-abide-validator='checkboxes' data-abide-validator-values='1,3'>
<input type="checkbox"/>
<input type="checkbox"/>
<input type="checkbox"/>
<input type="checkbox"/>
<input type="checkbox"/>
</div>
<script>
$(document).foundation({
validators: {
checkboxes: function(el, required, parent) {
var countC = el.find(':checked').length;
alert(countC);
}
}
});
</script>
At this point, I just try to count the checked inputs. But it seems I can't even trigger the validator... I think I could manage to code my validation stuff if only I could figure out how to trigger it.
Indeed I didn't find many examples of the custom validator, and the official doc did not help me much.
Your HTML markup is not really "correct" for abide. You should be attaching the data-abide-validator attribute to the inputs, not the parent div. Additionally, you need some better markup so abide's default error display can work (and some better use of foundation's grid system to lay it out). I would point you toward the Abide Validation Page on Zurb's site for some examples of form markup.
I've taken the liberty of restructuring your markup to be something that is more becoming of a foundation layout:
<form action="/echo/html/" method="POST" data-abide>
<div class="row">
<div class="small-12 columns checkbox-group" data-abide-validator-limit="1,3">
<label>Check some boxes</label>
<small class="error">You have checked an invalid number of boxes.</small>
<ul class="small-block-grid-3">
<li>
<label>
<input type="checkbox" data-abide-validator="checkbox_limit" value="1" /> 1
</label>
</li>
<li>
<label>
<input type="checkbox" data-abide-validator="checkbox_limit" value="2" /> 2
</label>
</li>
<li>
<label>
<input type="checkbox" data-abide-validator="checkbox_limit" value="3" /> 3
</label>
</li>
<li>
<label>
<input type="checkbox" data-abide-validator="checkbox_limit" value="4" /> 4
</label>
</li>
<li>
<label>
<input type="checkbox" data-abide-validator="checkbox_limit" value="5" /> 5
</label>
</li>
</ul>
</div>
</div>
<div class="row">
<div class="small-12 columns">
<button type="submit">Submit</button>
</div>
</div>
</form>
As to your JS code. It's not correct either. You need to address the abide -> validators namespace of the options, not just validators. I've rewritten your JS code to not only do that, but give the desired effect you wanted:
$(document).foundation({
abide: {
validators: {
checkbox_limit: function(el, required, parent) {
var group = parent.closest( '.checkbox-group' );
var limit = group.attr('data-abide-validator-limit').split(',');
var countC = group.find(':checked').length;
if( countC >= limit[0] && countC <= limit[1] ) {
group.find('small.error').hide();
//return true so abide can clear any invalid flags on this element
return true;
} else {
group.find('small.error').css({display:'block'});
//return false and let abide do its thing to make sure the form doesn't submit
return false;
}
}
}
}
});
In order to check adjacent elements when doing custom validation, you need to have something to target. The el variable in the validation function will be the DOM element of the input/field that is being validated. The required variable will tell you if the field is flagged as being required or not (boolean). The parent variable will be set to the "parent" of the field. I say "parent" because although the label tag is technically the parent of the input element, abide is smart enough to realize that the label is part of the field's element structure and skip over it to the li element instead.
From there, you need a way to identify a common parent. So I added the checkbox-group class to whatever element I decided to make the "parent" of all the checkboxes in the group. This is not a Foundation or Abide "magic" class, but rather something of my own creation for use in the validation function.
From there, you can easily trace the few lines of the validation function to see the workflow: Find the group container object, parse the limits off the container's data-abide-validator-limits attribute, count the number of checked inputs in the container, check if the number checked is between the limits, display/hide the error message and return true/false so abide knows if the field validated or not.
I've got a working Fiddle of it if you care to check it out yourself ;) Hopefully this was informative for you, and I wish you the best of luck playing with the awesome that is Foundation!