How to Validate Radio Buttons Field in angular with reactive Forms - javascript

I have name and values ,calling from the ts side and want to validate it.the values are'nt getting from the event and it's been comming such as (on) .
<form [formGroup]="reactiveForm">
<div *ngFor="let item of checkBoxValueList">
<input
type="radio"
formControlName="yourChoice"
[value]="item"
(change)="event($event)"
>
{{item}}
</div>
</form>
<pre>
{{reactiveForm.value | json}}
</pre>
checkBoxValueList = [
'Reading',
'Watching',
'Traveling',
'Cooking'
];
reactiveForm: FormGroup = new FormGroup({
yourChoice: new FormControl()
});
constructor() {}
edit(eve) {
console.log(eve);
console.log("target", eve.target.value);
}

You can pass directly your value instead of event.
Try it.
(change)="edit(item)".
Hope this helps.

I guess that you only need the selected value on change event and validate it. So here you can access the selected value of radio button by our reactiveForm variable.
event(eve) {
console.log(eve);
// console.log("target", eve.target.value);
console.log(this.reactiveForm.value['yourChoice']); //this will give your selected value
}
Hope this helps!!

Related

How to add Add button to enter dynamic value in Angular 2/4/6/8 Multiselect Dropdown?

I am trying to add dynamic add button angular2 multiselect. Any one has done this dynamic addition of user entered value by selecting Plus button. I have tried with addNewItemOnFilter: true, I'm not able to see any + button.
I am putting (onAddFilterNewItem)="onAddItem($event)" for using angular2-multiSelect.
In settings, I am having
addNewItemOnFilter: true in the settings file.
Still I am not getting an extra 'ADD' button to add extra field. Any help I would appreciate.
There You have dynamic multiselect buttons.
Updated as you want input inside.
Template:
<div *ngIf="buttons" class="btn-group">
<button *ngFor="let button of buttons" (click)="addDynaminMultiseletButton()">
{{button}} <input type="text" (click)="setInput($event)">
</button>
</div>
Component:
buttons = ['Another button']
input: string
constructor() { }
addDynaminMultiseletButton() {
this.buttons.push("" + this.input)
}
setInput(event: any) {
this.input = event.target.value
}
You can store them in database:
buttons$ = Observable<any[]>
constructor(private db: SomeDatabase){}
ngOnInit() {
this.buttons = this.db.collection('fancyButtons').valueChanges()
}
addDynaminMultiseletButton() {
this.db.collection('fancyButtons').add({ fancyButton: 'fancyButton' })
}
Remember to subscribe when you want to display async buttons:
Template:
<div *ngIf="buttons$ | async as buttons " class="btn-group">
<button *ngFor="let button of buttons" (click)="addDynaminMultiseletButton()">+</button>
</div>
Have a nice day and good luck with programming! Remember to assign at least one element in array so there will be at least one button on screen.

Remove the selected option from select box

I am making angular application with angular form.
Here i have given a form with input fields first name and last name which will always showing..
After that i am having children which will be displayed upon clicking the add button and the children will get removed on click remove button.
As of now everything works fine.
Here i am making patching of data to the inputs on click option from select box.. The neccessary inputs gets patched..
HTML:
<div>
<form (ngSubmit)="onSubmit()" [formGroup]="form">
<div *ngFor="let question of questions" class="form-row">
<ng-container *ngIf="question.children">
<div [formArrayName]="question.key">
<div *ngFor="let item of form.get(question.key).controls; let i=index" [formGroupName]="i">
<div *ngFor="let item of question.children">
<app-question [question]="item" [form]="form.get(question.key).at(i)"></app-question>
</div>
</div>
<select multiple (change)="changeEvent($event)">
<option *ngFor="let opt of persons" [value]="opt.key">{{opt.value}}</option>
</select>
</div>
</ng-container>
<ng-container *ngIf="!question.children">
<app-question [question]="question" [form]="form"></app-question>
</ng-container>
</div>
<div class="form-row">
<!-- <button type="submit" [disabled]="!form.valid">Save</button> -->
</div>
</form> <br>
<!-- Need to have add and remove button.. <br><br> -->
<button (click)="addControls('myArray')"> Add </button>
<button (click)="removeControls('myArray')"> Remove </button><br/><br/>
<pre>
{{form?.value|json}}
</pre>
</div>
TS:
changeEvent(e) {
if (e.target.value == 1) {
let personOneChild = [
{ property_name : "Property one" },
{ property_name : "Property two" },
]
for (let i = 0; i < personOneChild.length; i++) {
this.addControls('myArray')
}
this.form.patchValue({
'myArray': personOneChild
});
}
if (e.target.value == 2) {
let personTwoChild = [
{ property_name : "Property three" },
{ property_name : "Property four" },
{ property_name : "Property five" },
]
for (let i = 0; i < personTwoChild.length; i++) {
this.addControls('myArray')
}
this.form.patchValue({
'myArray': personTwoChild
});
}
}
addControls(control: string) {
let question: any = this.questions.find(q => q.key == control);
let children = question ? question.children : null;
if (children)
(this.form.get(control) as FormArray).push(this.qcs.toFormGroup(children))
}
removeControls(control: string) {
let array = this.form.get(control) as FormArray;
array.removeAt(array.length - 1);
}
Clear working stackblitz: https://stackblitz.com/edit/angular-x4a5b6-fnclvf
You can work around in the above link that if you select the person one option then the value named property one and property two gets binded to the inputs and in select box the property one is highlighted as selected..
The thing i am in need is actually from here,
I am having a remove button, you can see in demo.. If i click the remove button, one at last will be got removed and again click the last gets removed..
Here i am having two property one and two, if i remove both the inputs with remove button, the the highlighted value person one in select box needs to get not highlighted.
This is actually my requirement.. If i remove either one property then it should be still in highlighted state.. Whereas completely removing the both properties it should not be highlighted..
Hope you got my point of explanation.. If any needed i am ready to provide.
Note: I use ng-select for it as i am unable implement that library, i am making it with html 5 select box.. In ng-select library it will be like adding and removing the option.. Any solution with ng-select library also appreciable..
Kindly help me to achieve the result please..
Real time i am having in application like this:
Selected three templates and each has one property with one,two,three respectively:
If choose a dropdown then the property values for the respective will get added as children.
Here you can see i have deleted the property name three for which the parent is template three and the template three still shows in select box even though i removed its children
Firstly, get a reference to the select, like so:
HTML:
<select multiple (change)="changeEvent($event)" #mySelect>
<option *ngFor="let opt of persons" [value]="opt.key">{{opt.value}}</option>
</select>
TS:
import { ViewChild } from '#angular/core';
// ...
#ViewChild('mySelect') select;
Then, in your remove function, check if all elements have been removed, and if they have, set the value of the select to null
if (array.length === 0) {
this.select.nativeElement.value = null;
}
Here is a fork of the StackBlitz

Angular 4 nested form update

I've got the following 'triple level' nested form:
FormGroup->ArrayOfFormGroups->FormGroup
Top level (myForm):
this.fb.group({
name: '',
description: '',
questions: this.fb.array([])
});
Nested form array element for 'questions':
this.fb.group({
priority: ['1'],
params: this.fb.group({parameter: ['']})
});
Nested form group element for 'params' is a key:value object of random length.
I'm using the following ngFor to go through elements:
<tr *ngFor="let questionConfigForm of myForm.controls.questions.controls; let i=index" [formGroupName]="i">
...
<div *ngFor="let param of objectKeys(questionConfigForm.controls.params.controls)" formGroupName="params">
<input type="text" [formControlName]="param">
I've got the following behavior:
When I'm updating any of the fields on first two form levels I could instantly see changes in corresponding form controls values with {{myForm.value | json}}.
But if I input something in one of 'params' controls I couldn't see any changes in myForm values, but the form data for 'params' controls will be updated if I will make any changes in corresponding 'questions' form.
For me it looks like 'param' form control receives input data, but doesn't trigger some update event, and I don't know how to fix that, except writing my own function to react on (change) and patchValue in form..
So my question is how to make 'params' controls update myForm without that strange behavior?
UPD:
initQuestionConfig() {
return this.fb.group({
priority: ['1'],
params: this.fb.group({parameter: ['']}),
});
}
addQuestionConfig() {
const control = <FormArray>this.myForm.controls['questions'];
const newQuestionCfg = this.initQuestionConfig();
control.push(newQuestionCfg);
}
Finally the problem is solved.
The root of this issue was the way I've cleaned up already existing 'params'.
To remove all parameters from 'questions' I used the following code:
const control = <FormArray>this.myForm.controls['questions'];
control.controls[index]['controls'].params = this.fb.group([]);
And the reason of those glitches was this new 'fb.group' instance.
Now I'm removing params one by one, keeping original formGroup instance and it works as expected:
const control = <FormArray>this.myForm.controls['questions'];
const paramNames = Object.keys(control.controls[index]['controls'].params.controls);
for (let i = 0; i < paramNames.length; i++) {
control.controls[index]['controls'].params.removeControl(paramNames[i]);
}
#MilanRaval thanks for your time again :)
Try this: Give formArrayName and formGroupName like below...
<div formArrayName="testGroup">
<div *ngFor="let test of testGroup.controls; let i=index">
<div [formGroupName]="i">
<div class="well well-sm">
<label>
<input type="checkbox" formControlName="controlName" />
</div>
</div>
</div>
</div>

Angular 2 - Kendo UI Dropdown default value

I'm trying to create a dropdownlist using Kendo UI, it's working great except for having a default selected value when the screen loads.
according to their documentation my code should look like this:
HTML:
<kendo-dropdownlist formControlName="description"
[data]="definitionData.Languages"
[(ngModel)]="languageValue"
[textField]="'Value'"
[valueField]="'Key'"
[value]="2"
[valuePrimitive]="true">
</kendo-dropdownlist>
<span class="left col-xs-6">
<input type="text" id="descriptionField" class="form-control" [value]="getValue(descriptionForm.controls.description.value)" #descriptionField (blur)="updateDescriptionValue(descriptionField.value, languageValue)" />
</span>
COMPONENT:
public descriptionForm: FormGroup = new FormGroup({
description: new FormControl()
});
My dropdown works, but the default selected value is blank when I load the page, and it should be the object with Key: 2
note: I don't want to use [defaultItem] since It will just duplicate the item, meaning it will be in the dropdown list 2 times.
I've tried numerous things, but I can't figure out what I should do!
Thanks in advance
You should choose between value and ngModel binding. From documentation:
The DropDownList does not support the simultaneous usage of the value property and the ngModel value binding.
Solution with value property:
Delete ngModel from HTML.
Bind to valueChange event and set value in your model.
HTML:
<kendo-dropdownlist formControlName="description"
[data]="definitionData.Languages"
(valueChange)="handleValue($event)"
[textField]="'Value'"
[valueField]="'Key'"
[value]="2"
[valuePrimitive]="true">
</kendo-dropdownlist>
COMPONENT:
handleValue(value) {
this.languageValue = value;
}
Solution with ngModel property:
Delete value from HTML.
Set default value in your model.
HTML:
<kendo-dropdownlist formControlName="description"
[data]="definitionData.Languages"
[(ngModel)]="languageValue"
[textField]="'Value'"
[valueField]="'Key'"
[valuePrimitive]="true">
</kendo-dropdownlist>
COMPONENT:
constructor(){
this.languageValue = 2;
}

Angular2 : Ajax form data return null

I'm trying to set a dynamic form in Angular2.
So, in my ngOnInit function, I made a Ajax request to get a JSON with form data.
Like this :
export class CustomerEditComponent{
private customer : Customer = new Customer();
private customerForm;
constructor(private _CustomersService: CustomersService, private _routeParams: RouteParams, private _fb: FormBuilder){
this.customerForm = _fb.group({
name: [],
job: [],
arrival_date: []
});
}
ngOnInit(){
let id = this._routeParams.get('id');
this._CustomersService.getById(id).subscribe(res => {
this.customer = res;
});
}
onSubmit(event){
console.log(event);
}
}
So, at the component construct, 'customer' is equals to a newest one. (all properties are empty). But just after, we set value to every properties.
No problem for that, my input has the correct values.
But, if I submit my form, the form value is equals to :
Object {name: null, job: null, arrival_date: null}
(But the form in the view is correctly populate).
Here my form (condensed) :
<form [ngFormModel]="customerForm" (ngSubmit)="onSubmit(customerForm.value)">
<input md-input [(value)]="customer.name">
<input md-input [(value)]="customer.job">
<input md-input type="date" [(value)]="customer.arrival_date">
<button type="submit">Save</button>
</form>
I use [(value)] cause ng2-material package. (I already try with ngControl).
I think my code is 'wrong' about this feature, but I dunno where.
Thanks !
EDIT :
I have found the answer !
With ng2-material, we need to set [(value)] and [(ngModel)] together on every input like this :
<form [ngFormModel]="customerForm" (ngSubmit)="onSubmit(customerForm)">
<input md-input [(value)]="customer.name" [(ngModel)]="customer.name">
<input md-input [(value)]="customer.job" [(ngModel)]="customer.job">
<input md-input type="date" [(value)]="customer.arrival_date" [(ngModel)]="customer.arrival_date">
<button type="submit">Save</button>
</form>
[(value)] is used by ng2-material to set the value 'on front'.
I think that the problem is that you didn't associate your form inputs with their controllers within the ngFormControl directive in your template. You should refactor that way:
<form [ngFormModel]="customerForm" (ngSubmit)="onSubmit(customerForm.value)">
<input md-input [(value)]="customer.name"
ngFormControl="name">
<input md-input [(value)]="customer.job"
ngFormControl="job">
<input md-input type="date" [(value)]="customer.arrival_date"
ngFormControl="arrival_date">
<button type="submit">Save</button>
</form>
See this link from ng2-material samples: https://github.com/justindujardin/ng2-material/blob/master/examples/components/input/form_builder.html
Otherwise why don't you use the customer object instead of the customerForm.value one?
Hope it helps you,
Thierry

Categories

Resources