How to check the validity of form control in side form array? - angular-reactive-forms

I am unable to check the validity of form controls inside form group
Please check below code (number of form arrays are dynamic)
this.invoiceForm = this.builder.group({
itemRows: this.builder.array([this.initItemRows()],[Validators.required])
});
initItemRows() {
return this.builder.group({
colName: ['', [Validators.required]],
equat: ['>=', [Validators.required]],
filValue: ['', [Validators.required, Validators.min(0.01)]]
});
}
HTML code
<form [formGroup]="invoiceForm">
<div formArrayName="itemRows">
<div *ngFor="let itemrow of invoiceForm.controls.itemRows.controls;let i = index" [formGroupName]="i"
style="display: flex;align-items: center;">
<div style="width: 45%;">
<mat-form-field style="width: 95%;">
<mat-select placeholder="Cohort" formControlName="colName">
<mat-option *ngFor="let item of filterCohortData()"
value="{{item.columnName}}" [disabled]="item.isDisabled">
{{item.columnName}}
</mat-option>
</mat-select>
</mat-form-field>
</div>
<div style="width: 20%;text-align: center;">
<span>>=</span>
</div>
<div style="width: 25%;">
<mat-form-field style="width: 95%;">
<input type="number" min ="0.01" step="1" matInput autocomplete="off" placeholder="Value" formControlName="filValue" />
</mat-form-field>
</div>
<div style="width: 10%;">
<span *ngIf="i == 0" (click)="addNewRow()" matTooltip="Add Column" [ngClass]="{'noti-disable': invoiceForm.value.itemRows.length == colHeaders.length}">
<mat-icon>add_box</mat-icon>
</span>
<span *ngIf="i != 0" (click)="deleteRow(i, true)" matTooltip="Delete Column">
<mat-icon>indeterminate_check_box</mat-icon>
</span>
</div>
</div>
</div>
</form>
{{invoiceForm.get('itemRows').status}}
<div class="btn-div">
<button (click)="saveEqu()" *ngIf="filterType.value =='COLUMNWISE'" [disabled]="invoiceForm.invalid">Save</button>
<button (click)="close()" style="margin-left: 20px;">Cancel</button>
</div>
If i am deleting the value of filValue form control then Save button should be in disabled state

I have created a formarray and have added the validation. If formarray has 0 elements in it then I have disabled the submit button. this.formarray.invalid returns true or false based on whether form is valid or not.
I have used user example where user has firstname, lastname and age where firstname and lastname are compulsory fields so if user has not entered firstname or lastname the submit button stays disabled.
Here is the link of stackblitz where I have tried to solve your problem. When you delete/remove all values from formarray the submit button gets disabled.
If there is something which I have missed please let me know I would be happy to help

Related

Why is my *ngIf condition not recognizing the error and displaying the message when the condition is met?

I have a custom validator that I am applying to an input field. My ngIf condition should display an error message if the form value has an error specific to the custom validator. It does not display the message, I cannot figure out why.
In my TS file:
export class ParentFinancialComponent implements OnInit {
// Set selected section value on load time.
selectedSectionGroup = {
sectionOne: false,
sectionTwo: true,
sectionThree: true,
sectionFour: true,
sectionFive: true,
sectionSix: true
};
public financialSectionTwo: FormGroup;
ngOnInit() {
this.initForm();
}
initForm() {
this.financialSectionTwo = this.formBuilder.group({
parents2017AdjustedGrossIncome: ['', [CustomValidators.onlyNumbers]],
parents2017IncomeTaxAmount: ['', [CustomValidators.onlyNumbers]],
parents2017TaxExemption: ['', [CustomValidators.onlyNumbers]]
});
get sectionTwo() { return this.financialSectionTwo.controls; }
}
In my HTML:
<div [hidden]="selectedSectionGroup.sectionTwo" class="tab-pane
fade show active"
id="{{financialSectionEnum.SECTION_TWO}}" role="tabpanel">
<form [formGroup]="financialSectionTwo">
<p class="section-header">Section II</p>
<div class="form-group row"
[hidden]="sectionOne.parentsIrsStatus.value === '3'">
<p class="col-lg-9"><b class="q-num">89)</b><span
[hidden]="sectionOne.parentsIrsStatus.value !== '1'"
class="form-required">*</span>Income for 2017?<i
class="fa fa-info-circle" aria-hidden="true"></i></p>
<div class="col-lg-3">
<label class="sr-only">Adjusted gross
income</label>
<div class="input-group mb-2">
<div class="input-group-prepend">
<div class="input-group-text">$</div>
</div>
<input
maxlength="9"
formControlName="parents2017AdjustedGrossIncome"
id="parents2017AdjustedGrossIncome"
type="text"
class="form-control col-3 col-lg-12"
data-hint="yes"
>
<div class="input-group-append">
<div class="input-group-text">.00</div>
</div>
<div
*ngIf="sectionTwo.parents2017AdjustedGrossIncome.touched &&
sectionTwo.parents2017AdjustedGrossIncome.errors.onlyNumbers"
class="alert text-danger m-0 p-0 col-md-12"
>
Enter an amount
</div>
</div>
</div>
If i enter an alphabet, I should get the error message "Enter an amount". I have other inputs that depend on multiple custom validators, so checking to see if the input field is just "invalid" will help me. I need the message to display only if a specific custom validator is triggered.
You didn't include the implementation for your custom validator: CustomValidators.onlyNumbers so can't say what is wrong with the logic... however, the following implementation could get what you wanted !!
validator:
CustomValidatorsOnlyNumbers(control: AbstractControl) {
var pattern = /^\d+$/;
if ( pattern.test(control.value) == true ){ return true;} else {
return { onlyNumbers: true };
}
}
relevant HTML:
<div class="tab-pane fade show active"
role="tabpanel">
<form [formGroup]="financialSectionTwo">
<p class="section-header">Section II</p>
<div class="form-group row" >
<p class="col-lg-9"><b class="q-num">89)</b><span
class="form-required">*</span>Income for 2017?<i
class="fa fa-info-circle" aria-hidden="true"></i></p>
<div class="col-lg-3">
<label class="sr-only">Adjusted gross
income</label>
<div class="input-group mb-2">
<div class="input-group-prepend">
<div class="input-group-text">$</div>
</div>
<input
maxlength="9"
formControlName="parents2017AdjustedGrossIncome"
type="text"
class="form-control col-3 col-lg-12"
data-hint="yes"
>
<div class="input-group-append">
<div class="input-group-text">.00</div>
</div>
<div
*ngIf="financialSectionTwo.get('parents2017AdjustedGrossIncome').touched && financialSectionTwo.get('parents2017AdjustedGrossIncome').hasError('onlyNumbers')"
class="alert text-danger m-0 p-0 col-md-12"
>
Enter an amount
</div>
</div>
</div>
</div>
</form>
</div>
complete working stackblitz here

Vue.js - Buefy Modules (Radio btns/ Check Box)

I'm practising back-end in Laravel, and for front-end I'm using Vue.js - Buefy Modules, and I have little problem with Radio and CheckBox.
Here User should choose one of the two offered radio btns:
<div class="block">
<b-radio-group v-model="permissionType">
<b-radio name="permission_type" value="basic">Basic Permission</b-radio>
<b-radio name="permission_type" value="crud">CRUD Permission</b-radio>
</b-radio-group>
</div>
If User click on first btun (Basic) there should appear 3 input fields:
<div class="field" v-if="permissionType == 'basic'">
<label for="display_name" class="label">Name (Display Name)</label>
<p class="control">
<input type="text" class="input" name="display_name" id="display_name">
</p>
</div>
<div class="field" v-if="permissionType == 'basic'">
<label for="name" class="label">Slug</label>
<p class="control">
<input type="text" class="input" name="name" id="name">
</p>
</div>
<div class="field" v-if="permissionType == 'basic'">
<label for="description" class="label">Description</label>
<p class="control">
<input type="text" class="input" name="description" id="description" placeholder="Describe what this permission does">
</p>
</div>
If User click on second btn (CRUD) there should appear 1 input, 4 check box btns and table, but they do not appear.
<div class="field" v-if="permissionType == 'crud'">
<label for="resource" class="label">Resource</label>
<p class="control">
<input type="text" class="input" name="resource" id="resource" v-model="resource" placeholder="The name of the resource">
</p>
</div>
<div class="columns" v-if="permissionType == 'crud'">
<div class="column is-one-quarter">
<b-checkbox-group v-model="crudSelected">
<div class="field">
<b-checkbox custom-value="create">Create</b-checkbox>
</div>
<div class="field">
<b-checkbox custom-value="read">Read</b-checkbox>
</div>
<div class="field">
<b-checkbox custom-value="update">Update</b-checkbox>
</div>
<div class="field">
<b-checkbox custom-value="delete">Delete</b-checkbox>
</div>
</b-checkbox-group>
</div> <!-- end of .column -->
<input type="hidden" name="crud_selected" :value="crudSelected">
<div class="column">
<table class="table" v-if="resource.length >= 3">
<thead>
<th>Name</th>
<th>Slug</th>
<th>Description</th>
</thead>
<tbody>
<tr v-for="item in crudSelected">
<td v-text="crudName(item)"></td>
<td v-text="crudSlug(item)"></td>
<td v-text="crudDescription(item)"></td>
</tr>
</tbody>
</table>
</div>
</div>
I've checked Buefy documentation and there were some updates, but when I change code, still not works..
Here is script:
<script>
var app = new Vue({
el: '#app',
data: {
permissionType: 'basic',
resource: '',
crudSelected: ['create', 'read', 'update', 'delete']
},
methods: {
crudName: function(item) {
return item.substr(0,1).toUpperCase() + item.substr(1) + " " + app.resource.substr(0,1).toUpperCase() + app.resource.substr(1);
},
crudSlug: function(item) {
return item.toLowerCase() + "-" + app.resource.toLowerCase();
},
crudDescription: function(item) {
return "Allow a User to " + item.toUpperCase() + " a " + app.resource.substr(0,1).toUpperCase() + app.resource.substr(1);
}
}
});
</script>
Here I place original code without changes, if someone could fix this, I would be grateful. Thanks!
you forget to add v-model to your radio group, try this and it should work
<div class="block">
<b-radio-group v-model="permissionType">
<b-radio v-model="permissionType" name="permission_type" native-value="basic">Basic Permission</b-radio>
<b-radio v-model="permissionType" name="permission_type" native-value="crud">CRUD Permission</b-radio>
</b-radio-group>

How to validate a radio button in a form Angular 5

I have the following form where I want to validate the mat-radio-group as well, but since it does not support formControl I don't know how can I achieve that?
Anyone knows?
Here is my HTML
<h2 class="mat-title" style="text-align:center;">Register as a {{person}}</h2>
<form class="example-form" [formGroup]="registerForm" (submit)="onSubmit(registerForm)" novalidate>
<div class="example-selected-valuec mat-subheading-2">Your gender is: {{gender}}</div>
<mat-radio-group class="example-radio-group" [(ngModel)]="gender" [ngModelOptions]="{standalone: true}">
<mat-radio-button class="example-radio-button" *ngFor="let gender of genders" [value]="gender">
{{gender}}
</mat-radio-button>
</mat-radio-group>
<br>
<!--<div *ngIf="registerForm.controls.gender.invalid && (registerForm.controls.gender.dirty || registerForm.controls.gender.touched)"
class="alert alert-danger">
<div class="error mat-body-2" *ngIf="registerForm.controls.gender.errors.required">
You must fill out your gender
</div>
</div>-->
<mat-form-field class="example-full-width">
<input id="username" formControlName="username" matInput placeholder="Username">
</mat-form-field>
<div *ngIf="registerForm.controls.username.invalid && (registerForm.controls.username.dirty || registerForm.controls.username.touched)"
class="alert alert-danger">
<div class="error mat-body-2" *ngIf="registerForm.controls.username.errors.required">
You must fill out your username
</div>
<div class="error mat-body-2" *ngIf="registerForm.controls.username.errors.email && !registerForm.controls.username.errors.required">
Invalid email address
</div>
</div>
<button id="register" mat-raised-button color="primary" type="submit" [disabled]="registerForm.invalid">Register</button>
</form>

view new div based on option value of select tag using laravel

i have a dropdown list when i select any one option from list i should display an another form with name of the teacher and subject of the teacher in textbox.The form is not displaying.when i select one item it should display the selected name and description box to add subjects of teachers that they interested please help me
view page
<div class="portlet light bordered row">
<h1>Add teacher subject</h1>
<div class="row">
<form action = "{{ url('subjectby/adding/process') }}" method = "POST">
{{ csrf_field() }}
<div class= "col-md-12">
<div class="form-group">
<h3>Choose Teachers </h3>
<div class="input-group">
<div class="ui-widget border-dropdown" style="margin-left:50px;">
<select id="teacher" name="teachers" placeholder="Select Teacher">
<option value="">Select Teacher</option>
#foreach($user as $tec)
<option value="{{$tec->id}}">{{$tec->name}}</option>
#endforeach
</select>
</div>
</div>
</div>
</div>
<div class="col-md-12">
<div class="new">
<div class="form-group">
<div class="col-sm-6">
<label for="inputFacebook">Teacher Name</label>
<input type=hidden value="{{$tec->id}}" name="id">
<input type="text" value="{{$tec->name}}" class="form-control" name="name">
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<label for="inputDescription">Subject Interested</label>
<textarea class="form-control" rows="8" name="intr" placeholder="Enter Subject Interest"> </textarea>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="submit" value="add" name=b1>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
This isn't a Laravel specific problem. You are taking about DOM manipulation and so you best bet is to use jQuery or Vuejs or even vanilla Javascript if you so choose. Basically, you will write a script to watch for when your <select> changes, and then based on it's new value, show the part of the form you want.
Keep in mind that Laravel is a backend framework and so the user will never interact with it on a page. After a page loads, Laravel has done all it can do until another request is made. This is why Javascript was born - to let the user change things without reloading the page.

How to do autocomplete validation in Angular2?

I have been trying to implement an auto-complete to an input in my form in angular2. I want to show second hidden div if the input is invalid. Could you help me how to do that please?
<div class="form-group">
<div *ngSwitchCase="'organisation'">
<label [attr.for]="parameter.ObjectID" [innerHtml]="parameter.paramLabel"> </label>
<input [id]='parameter.ObjectID' class="form-control" type="text" [(ngModel)]="parameter.value" (keyup)="filter()" (change)="filter()" (blur)="filter()" [required]="parameter.mandatory" name="mandatory" #mandatory="ngModel">
<div *ngIf="companyNames.length > 0">
<ul *ngFor="let item of filteredCompanyList">
<li>
<a (click)="select(item)">{{item}}</a>
</li>
</ul>
</div>
<div [hidden]="!parameter.mandatory || mandatory.valid || mandatory.pristine" class="alert alert-danger">Please do not leave this field blank</div>
<div [hidden]="temp(mandatory)" class="alert alert-danger">The organisation entered was either not found or does not subscribe to the product</div>
</div>
The second hidden div will be displayed if your function temp() returns false.
All your checks (input valid?) you have to do in this function.
UPDATE:
Just use this [hidden]="filteredCompanyList.length > 0" to show/hide your div.

Resources