Form array validation not working in Angular 2 - angular2-forms

This is my form object
this.userFormGroup = this.fb.group({
name : ["", Validators.required],
email : "",
phone : ""
address : this.fb.group({
city : ["", Validators.required],
state : ""
}),
hobbies : this.fb.array([
this.fb.group({
name : ["", Validators.required]
}),
])
})
I have used this object in the below mentioned HTML.
<div formArrayName="hobbies">
<div formGroupName="0">
Name <input type="text" formControlN!ame="name"> <br><br>
<div *ngIf="userFormGroup.get('hobbies[0].city').hasError('required')">
City Required
</div>
</div>
</div>
Other validations are working but form validations are not working.
Thanks in advance.

Try this
<div *ngIf="userFormGroup.get('hobbies').controls[i].get('name').errors">
City Required
</div>

Related

Auto-Complete in AMP with POST method

I have a problem in AMP page. I want to build a page with AutoComplete list selection like jquery AutoComplete.
Amp give Example for Autocomplete Selection. But there is a problem. I have API with POST Method in this example I don't know how to set Request method Post in it with a different origin.
<div class="form-item city-state">
<label>City</label>
<input name="city"
type="text"
on="
input-debounced:
AMP.setState({
query: event.value,
showDropdown: event.value,
}),
autosuggest-list.show;
tap:
AMP.setState({
query: query == null ? '' : query,
showDropdown: 'true'
}),
autosuggest-list.show"
[value]="query || ''"
value=""
required
autocomplete="off" />
</div>
<div class="suggest">
<div class="autosuggest-container hidden"
[class]="(showDropdown && query) ?
'autosuggest-container' :
'autosuggest-container hidden'">
<amp-list class="autosuggest-box"
layout="fixed-height"
height="120"
src="/advanced/autosuggest/search_list"
[src]="query ?
autosuggest.endpoint + query :
autosuggest.emptyAndInitialTemplateJson"
id="autosuggest-list">
<template type="amp-mustache">
<amp-selector id="autosuggest-selector"
keyboard-select-mode="focus"
layout="container"
on="
select:
AMP.setState({
query: event.targetOption,
showDropdown: false
}),
autosuggest-list.hide">
{{#results}}
<div class="select-option no-outline"
role="option"
tabindex="0"
on="tap:autosuggest-list.hide"
option="{{.}}">{{.}}</div>
{{/results}} {{^results}}
<div class="select-option {{#query}}empty{{/query}}">
{{#query}}Sorry! We don't ship to your city 😰{{/query}}
</div>
{{/results}}
</amp-selector>
</template>
</amp-list>
</div>
</div>
<amp-state id="autosuggest">
<script type="application/json">
{
"endpoint": "/advanced/autosuggest/search_list?q=",
"emptyAndInitialTemplateJson": [{
"query": "",
"results": []
}]
}
</script>
</amp-state>

Send an Object data vit GET with AngularJS error

I'm having a problem with my GET request to API, here is:
self.search = {
init_date: new Date(),
end_date: new Date(),
statuses: {"Aberto": false, "Em andamento": false, "Fechado": false},
district: null,
address: null,
tags: null
};
$http.get(apiUrl + requestEndpoint + 'search', {params: self.search}).then(function(response){
self.gridOptions.data = response.data;
});
So, what is happening is that my params in API looks like this
{"end_date"=>"2016-07-07T22:58:11.943Z",
"init_date"=>"2016-07-07T22:58:11.943Z",
"statuses"=>"{\"Aberto\":false,\"Em andamento\":false,\"Fechado\":false}",
"format"=>:json,
"controller"=>"api/v1/requests",
"action"=>"search"}
and then I cannot read the statuses because it's a kind of string. How should I solve that?
Just to know... My Statuses value come from form in HTML with checkboxes
<div class="form-group">
<h5>Status</h5>
<div class="col-sm-12">
<input type="checkbox" name="status" id="aberto" class="k-checkbox" value="Aberto" ng-model="reportsCtrl.search.statuses['Aberto']">
<label class="k-checkbox-label" for="aberto"> Aberto </label>
<input type="checkbox" name="status" id="em-andamento" class="k-checkbox" value="Em andamento" ng-model="reportsCtrl.search.statuses['Em andamento']">
<label class="k-checkbox-label" for="em-andamento"> Em andamento </label>
<input type="checkbox" name="status" id="fechado" class="k-checkbox" value="Fechado" ng-model="reportsCtrl.search.statuses['Fechado']">
<label class="k-checkbox-label" for="fechado"> Fechado </label>
</div>
</div>
PS: My API is Rails
Regards.

How to bind ngFormModel in angular2 using Dart?

The following works in a form (the form is displayed)
.html
<form (ngSubmit) = "onSubmit()"
#nameForm = "ngForm">
{{diagnostic}}
<div class = "mdl-card mdl-shadow--3dp layout horizontal wrap">
<div class = "mdl-card__title">
<h2 class = "mdl-card__title-text">Name</h2>
</div>
<div
class = "mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<input
required
type = "text"
[(ngModel)] = "name.first"
ngControl = "first"
#first = "ngForm"
(input)="onInputHandler($event)"
class = "mdl-textfield__input ng-valid"
id = "first">
<label
class = "mdl-textfield__label"
for = "first">First</label>
<span [hidden] = "isFirstValid"
class = "mdl-textfield__error">{{firstErrorMsg}}</span>
</div>
<div class =
"mdl-card__actions mdl-card--border">
<button id = "startButton"
class = "mdl-button mdl-js-button mdl-button--raised mdl-button--accent mdl-js-ripple-effect"
>Submit
</button>
<br>
<button class = "mdl-button mdl-js-button mdl-button--raised mdl-button--colored">
Button All
</button>
</form>
Trying to follow the example at Forms and Validation in Angular 2.0,
I cannot get the UI to display by changing the first line of the form to
<form (ngSubmit) = "onSubmit()"
[ngFormModel]="form" #f="form">
{{diagnostic}}
..
With the change the browser simply does not display anything as if it cannot parse the markup - the error is actually shown in pub-serve or debug mode.
Transform TemplateCompiler on epimss_ng2_reg|lib/components/name_component.ng_meta.json threw error: Template parse errors:
There is no directive with "exportAs" set to "form" ("
<div [hidden] = "isSubmitted">
<form (ngSubmit) = "onSubmit()"
[ng-form-model]="form" [ERROR ->]#f="form">
{{diagnostic}}
<div class = "mdl-card mdl-shadow--3dp layout horizontal wrap">
"): NameComponent#12:31
....
Why is this not working?
Seems this was changed since when the blog post was created.
NgForm is now exported as ngForm instead of form.
[ngFormModel]="form" #f="ngForm">
It's correct in the GitHub source but not in the blog post.
Full component according to the example in the blog post in Dart
#Component(selector: 'form-element')
#View(template: '''
<h1>form-element</h1>
<form (ngSubmit)="onSubmit()" [ngFormModel]="form" #f="ngForm">
<div>
<div class="formHeading">First Name</div>
<input type="text" id="firstName" ngControl="firstName">
<div class="errorMessage" *ngIf="f.form.controls['firstName'].touched && !f.form.controls['firstName'].valid">First Name is required</div>
</div>
<div>
<div class="formHeading">Street Address</div>
<input type="text" id="firstName" ngControl="streetAddress">
<div class="errorMessage" *ngIf="f.form.controls['streetAddress'].touched && !f.form.controls['streetAddress'].valid">Street Address is required</div>
</div>
<div>
<div class="formHeading">Zip Code</div>
<input type="text" id="zip" ngControl="zip">
<div class="errorMessage" *ngIf="f.form.controls['zip'].touched && !f.form.controls['zip'].valid">Zip code has to be 5 digits long</div>
</div>
<div>
<div class="formHeading">Address Type</div>
<select id="type" ngControl="type">
<option [value]="'home'">Home Address</option>
<option [value]="'billing'">Billing Address</option>
</select>
</div>
<button type="submit" [disabled]="!f.form.valid">Save</button>
<div>
<div>The form contains the following values</div>
<div>
{{payLoad}}
</div>
</div>
</form>
''')
class FormElement {
ControlGroup form;
String payLoad;
FormElement(FormBuilder fb) {
form = fb.group({
"firstName": ['', Validators.required],
"streetAddress": ['', Validators.required],
"zip": [
'',
Validators.compose([ZipValidator.validate])
],
"type": ['home']
});
}
void onSubmit() {
payLoad = JSON.encode(this.form.value);
}
}

Dynamically add multiple fields to be validated using bootstrap validator

I have gone through the example here. But it illustrates dynamic addition of a single input field. I have to add multiple dynamic input fields. How can I achieve it? Refer this example jsfiddle
I need to dynamically add all the three fields in the table row on clicking button through.
You can try somethings like this:
<form id="myForm" action="myAction">
<div class="row" id="line_1">
<div class="col-md-2 form-group">
<input type="text" class="form-control input-sm" id="idFirstField_1" name="firstField[]">
</div>
<div class="col-md-2 form-group">
<input type="text" class="form-control input-sm" id="idSecondField_1" name="secondField[]">
</div>
<div class="col-md-2 form-group">
<input type="text" class="form-control input-sm" id="idThirdField_1" name="thirdField[]">
</div>
</div>
<a id="cloneButton">add line</a>
</form>
In the JavaScript file you must to use the function clone() and to change the id of each input if you want:
$(document).ready(function () {
var count = 2;
$('#cloneButton').click(function () {
var klon = $('#line_1');
klon.clone().attr('id', 'line_' + (++count)).insertAfter($('#line_1'));
$('#line_' + count).children('div').children('input').each(function () {
$(this).val('');
var oldId = $(this).attr('id').split('_');
$(this).attr('id', oldId[0] + '_' + count);
});
});
//if you want to validate the fields, then you can use this code:
$('#myForm').bootstrapValidator({
fields: {
'firstField[]': {
validators: {
notEmpty: {
message: 'Enter a value'
}
}
},
'secondField[]': {
validators: {
notEmpty: {
message: 'Enter a value'
}
}
},
'thirdField[]': {
validators: {
notEmpty: {
message: 'Enter a value'
}
}
}
}
});
});
Now the bootstrap validation does not will work for cloned fields because you must to use in the JavaScript file somethings like this
$('#myForm').bootstrapValidator('addField', $option); //(from your link http://bootstrapvalidator.com/examples/adding-dynamic-field/ )
but who will contains all fields. I don't now how to do it.

About bean of hasErrors

Assuming i have the following object in my controller
objCollection = [obj1, obj2, obj3]
And in each obj is the following
obj1 = [
input = value, inputA1 = valueA1, inputA2 = valueA2
]
obj2 = [
input = value, inputB2 = valueB2, inputA3 = valueA3
]
obj3 = [
input = value, inputC2 = valueC2, inputA3 = valueA3
]
And my GSP looks something like this
<div class="control-group ${hasErrors(bean: objCollection.obj, field: 'input', 'error')}">
<g:textField name='input' value='${objCollection?.obj}'>
</div>
<div id="subForm" class="subContainer">
<g:each var='obj' in='${objCollection}' status='a'>
<div id='obj${a+1}'>
<div class='subaccordion'>
<div>
<g:each var='objInstance' in='${obj}' status="b">
<g:render template="miniForm" model="[b:b, objInstance:objInstance]"/>
</g:each>
</div>
</div>
</div>
</g:each>
</div>
While for the template miniForm
<div class="control-group ${hasErrors(bean: objInstance, field: 'input', 'error')}">
<g:textField name='input' value='${objInstance?.obj}'>
</div>
<div class="control-group ${hasErrors(bean: objInstance, field: 'input', 'error')}">
<g:textField name='input' value='${objInstance?.obj}'>
</div>
Where the name attribute is changed using jquery to input A1, A2, B1, B2, C1 and C3 upon form load.
Now my question is, did i passed the object properly to the bean on hasErrors? Because i tried to get the hasErrors to work but somehow it didn't work to my expectation.
Did i made any mistake anywhere?
Also did i map the object correctly to every input in GSP? I'm not quite sure on how to use the safe operator '?' to avoid nullPointer error.

Resources