I want that when the user checks on checkbox, the value be "l.code" instead of a Boolean value
Here's my code
<div class="form-group">
<label>Critères : </label>
<div class="checkbox-inline" *ngFor="let l of lesCriteres; let i= index">
<label>
<input type="checkbox" [value]="l.code" [(ngModel)]="actif.lesCriteresActifs[i].critere.code">{{l.code}}
</label>
</div>
</div>
But it does not work ! when I check, it gives me "true" instead of "l.code". Thanks !
You can use "change" event handler with event binding on checkbox.
In html
<form>
<div *ngFor="let l of lesCriteres">
<input type="checkbox" value="l.code" (change)="onChangeEvent($event, l.code)"> {{l.code}}<br>
</div>
</form>
In ts
onChangeEvent(eventValue, valueOfCheckbox){
alert(valueOfCheckbox);
}
You can do something like below :
HTML:
<div *ngFor="let data of emails">
<input type="checkbox" [value]="data.email" (change)="onChange(data.email, $event.target.checked)"> {{data.email}}<br>
</div>
ts:
import { Component } from '#angular/core';
import { FormGroup, FormBuilder, FormArray, FormControl } from '#angular/forms';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
name = 'Angular 6';
emailFormArray = [];
emails = [{ email: "email1" }, { email: "email2" }, { email: "email3" }, { email: 'email4' }]
myForm: FormGroup;
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.myForm = this.fb.group({
useremail: this.fb.array([])
});
}
onChange(email: string, isChecked: boolean) {
if (isChecked) {
this.emailFormArray.push(email);
} else {
let index = this.emailFormArray.findIndex(x =>{
console.log(x);
return x == email
});
console.log(index)
this.emailFormArray.splice(index,1);
}
console.log(this.emailFormArray)
}
}
STACKBLITZ
Related
After start FormControl to my form, they marked in green with ng-valid but didn't use it yet.
When writing text and clear the input it's go ng-invalid as needed and when the input is OK the ng-valid is back as needed.
How to start the fields without ng-valid ? No need any class in this input until it dirty.
Here is my html: (you can see validate need to work only after using one of the fields)
<form [formGroup]="mainForm">
<div class="card-body">
<div class="form-group">
<label for="customerID">ID</label>
<input
type="text"
class="form-control"
id="customerId"
formControlName="customerId"
(click)="validate()"
placeholder="e.g 123456789">
<span class="error invalid-feedback" *ngIf="customerIdInvalid">ID is important, numbers only!</span>
</div>
<div class="form-group">
<label for="firstName">First Name</label>
<input
type="text"
class="form-control"
id="firstName"
name="firstName"
formControlName="firstName"
(click)="validate()"
placeholder="First Name">
<span class="error invalid-feedback" *ngIf="firstName?.invalid">First name invalid, try again</span>
</div>
</div>
</form>
Here is my component:
import { Component, OnInit } from '#angular/core';
import { FormControl, FormGroup, Validators } from '#angular/forms'
#Component({
selector: 'new-customer',
templateUrl: './new-customer.component.html',
styleUrls: ['./new-customer.component.scss']
})
export class NewCustomerComponent implements OnInit {
mainForm = new FormGroup({
customerId: new FormControl(),
firstName: new FormControl()
});
constructor() {}
ngOnInit(): void {
}
get customerIdInvalid(){
return this.mainForm.get('customerId')?.invalid;
}
get firstName(){
return this.mainForm.get('firstName')
}
validate(){
this.mainForm.get('customerId')?.setValidators([Validators.required , Validators.pattern(/^-?([0-9]\d*)?$/) , Validators.minLength(6)]);
this.mainForm.get('firstName')?.setValidators([Validators.required , Validators.pattern('^[a-zA-Z]+$') , Validators.minLength(2)]);
}
}
I change my component to:
import { Component, OnInit } from '#angular/core';
import { FormControl, FormGroup, Validators } from '#angular/forms'
#Component({
selector: 'new-customer',
templateUrl: './new-customer.component.html',
styleUrls: ['./new-customer.component.scss']
})
export class NewCustomerComponent implements OnInit {
mainForm = new FormGroup({
customerId: new FormControl('',[Validators.required , Validators.pattern(/^-?([0-9]\d*)?$/) , Validators.minLength(6)]),
firstName: new FormControl('',[Validators.required , Validators.pattern('^[a-zA-Z]+$') , Validators.minLength(2)])
});
constructor() {}
ngOnInit(): void {
}
get customerId(){
return this.mainForm.get('customerId');
}
get firstName(){
return this.mainForm.get('firstName')
}
onSubmit(){
console.log(this.mainForm.valid);
if(this.mainForm.valid){
console.log(this.mainForm.value);
}
}
}
So now all my css with .ng-invalid changed to .ng-dirty.ng-invalid
In that way I will assure only inputs that used will be mark red.
I started to study angular, i created a single crud using Angular 9 and Spring boot, but i have a question, what I'm trying to do is to get the data of the table below and move it for a reactive form to upload the data.
How to solve the issue?
enter image description here
.
enter image description here
<form [formGroup]="form" (ngSubmit)="submit()">
<div class="form-group">
<label for="">Nome</label>
<input type="text" formControlName="nome" class="form-control">
</div>
<div class="form-group">
<label for="">email</label>
<input type="text" formControlName="email" class="form-control">
</div>
<div class="form-group">
<label for="">username</label>
<input type="text" formControlName="username" class="form-control">
</div>
<button class="btn btn-outline-primary"> Salvar</button>
<button [routerLink]="['/']" style="margin-left: 1%;" class="btn btn-outline-warning"> Voltar</button>
</form>
My app-routing.module.ts:
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { ShowContactComponent } from './Componets/contact/show-contact/show-contact.component'
import { CreateContactComponent } from './Componets/contact/create-contact/create-contact.component'
const routes: Routes = [
{path:'', component:ShowContactComponent},
{path:'create', component:CreateContactComponent},
{path:'create/:id', component:CreateContactComponent}
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
import { Component, OnInit } from '#angular/core';
import { FormBuilder, FormGroup, Validators } from '#angular/forms';
import { Contact } from '../contact-model/Contact';
import { ContactService } from '../../contact.service';
import { Router, ActivatedRoute } from '#angular/router';
#Component({
selector: 'app-create-contact',
templateUrl: './create-contact.component.html',
styleUrls: ['./create-contact.component.css']
})
export class CreateContactComponent implements OnInit {
form:FormGroup;
contacts:Contact[] = []
contact:Contact
constructor(private service:ContactService, private router:Router, private fb:FormBuilder, private AR:ActivatedRoute) { }
ngOnInit() {
// this.paramService();
this.validateForms();
}
submit(){
const formValue = this.form.value;
const contact:Contact = new Contact(formValue.nome, formValue.email ,formValue.username );
this.service.create(contact).subscribe(response =>{
this.contacts.push(response);
this.router.navigate([''])
console.log(response);
})
}
paramService(){
const formValue = this.form.value;
const contact:Contact = new Contact(formValue.nome, formValue.email ,formValue.username );
console.log(contact);
this.service.readOne(this.contact.id).subscribe(response =>{
this.form.patchValue({
nome: contact.nome,
email: contact.email,
username: contact.username
});
});
}
validateForms(){
this.form = this.fb.group({
nome: ['', Validators.required],
email: ['', Validators.required],
username: ['', Validators.required]
})
}
}
You can do it in this way:
validateForms(data?: Contact){
this.form = this.fb.group({
nome: [data.name || '', Validators.required],
email: [data.email || '', Validators.required],
username: [data.username || '', Validators.required]
})
}
Now you should pass the data to show in your form:
ngOnInit() {
// const contact: Contact = ...
this.validateForms(contact);
}
Please change 'validateForms' name to 'initForm'.
I have a list displayed in a dropdownlist, but it displays the default as a blank and not as the first item in the dropdown.
I have tried adding let i = 0 and then [selected]="i = 0", but this does not seem to set the default item to the first item, however I am receiving the correct value back from i.
Below is my code:
<div class="form-group">
<label for="userName">User Name</label>
<select formControlName="userName" class="form-control" (change)="userChange($event)">
<option *ngFor="let row of usersModel;let i = index" value="{{ row.id }}" [selected]="i == 0">{{ row.userName }} {{ i }}</option>
</select>
</div>
Here is my TypeScript File:
import { Component, OnInit } from '#angular/core';
import { UserAdminService } from '../../services/user-admin.service';
import { FormBuilder, Form, FormControl, FormGroup } from '#angular/forms';
import { Router } from '#angular/router';
#Component({
selector: 'lib-add-user-to-role',
templateUrl: './add-user-to-role.component.html',
styleUrls: ['./add-user-to-role.component.css']
})
export class AddUserToRoleComponent implements OnInit {
addUserToRoleForm: FormGroup;
rolesModel: any[];
usersModel: any[];
selectedRole: string;
selectedUser: string;
constructor(private userAdminService: UserAdminService, private formBuilder: FormBuilder, private router: Router) {
var roleControl = new FormControl('');
var userControl = new FormControl('');
this.addUserToRoleForm = formBuilder.group({ roleName: roleControl, userName: userControl });
}
ngOnInit() {
this.userAdminService.getRoles().subscribe(roles => {
this.rolesModel = roles;
this.selectedRole = this.rolesModel[0].name;
this.userAdminService.getUsersNotInRole(this.selectedRole).subscribe(users => {
this.usersModel = users;
this.selectedUser = this.usersModel[0].id;
console.log(this.usersModel[0].userName);
this.addUserToRoleForm.controls['roleName'].setValue(this.rolesModel[0].name);
this.addUserToRoleForm.controls['userName'].setValue(this.usersModel[0].userName);
});
});
}
userChange(event: any) {
this.selectedUser = event.target.value;
console.log('Selected ' + this.selectedUser);
}
AddUserToRole() {
this.userAdminService.addUserToRole(this.selectedUser, this.selectedRole)
.subscribe(result => {
if (result.success) {
this.router.navigate(['/roleusermaint']);
}
else {
console.log('Error Received on adding user to role');
}
});
}
}
As you can see I added {{ i }} in the text to make sure it shows the value of i and it does:
What am I missing ?
Thanks for any help!
#Axle, if you're using a Reactive Form, you needn't use [selected] nor (change), just, when you create the form you give value to userName
Using the constructor
const firstId=usersModel[0].id
this.form=new FormGroup({
userName:new FormControl(firstId)
})
Using formBuilder
const firstId=usersModel[0].id
this.form=this.fb.group({
userName:firstId
})
Using setValue, after create the form
const firstId=usersModel[0].id
this.form.get('userName').setValue(firstId)
As you are using Angular reactive form, try to keep the logic in ts file itself.
Using setValue(), you can set the default value to a control.
To set the default value to form control you could to it like,
this.form.controls['country'].setValue(this.countries[0].id)
In template use it like,
<option *ngFor="let country of countries" [value]="country.id">
{{ country.name }}
</option>
Working Stackblitz
Ref:
A complete sample code would be something like,
app.component.ts
import { Component } from '#angular/core';
import { FormGroup, FormControl } from '#angular/forms';
import {Country} from './country';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
countries = [
{
id: 'us',
name: 'United States'
},
{
id: 'uk',
name: 'United Kingdom'
},
{
id: 'ca',
name: 'Canada'
}
];
form: FormGroup;
ngOnInit(){
this.form = new FormGroup({
country: new FormControl('')
});
this.form.controls['country'].setValue(this.countries[0].id)
}
}
app.component.html
<form [formGroup]="form">
<select formControlName="country">
<option *ngFor="let country of countries" [value]="country.id">
{{ country.name }}
</option>
</select>
</form>
I need to make a working search box. This code doesn't work. Can you help me to fix it?
html:
<form #f="ngForm" (ngSubmit)="onSubmit(f)" #searchForm="ngForm">
<input type="search" placeholder="Search...">
</form>
search-form Component:
#Component({
selector: 'app-search-form',
templateUrl: './search-form.component.html',
styleUrls: ['./search-form.component.css']
})
export class SearchFormComponent {
users: User[];
private s: String;
constructor(private route: ActivatedRoute,
private router: Router,
private userService: UserService) { }
onSubmit(f: NgForm) {
this.userService.findByFS(f.value).subscribe(data => {
this.users = data;})
}
}
I modified your code. It should work like that. You can check usage at https://angular.io/api/forms/NgForm.
Template:
<form #f="ngForm" (ngSubmit)="onSubmit(f)">
<input name="search" type="search" ngModel placeholder="Search...">
</form>
Component:
#Component({
selector: 'app-search-form',
templateUrl: './search-form.component.html',
styleUrls: ['./search-form.component.css']
})
export class SearchFormComponent {
users: User[];
constructor(private userService: UserService) {}
onSubmit(f: NgForm) {
this.userService.findByFS(f.value.search).subscribe(data => this.users = data);
}
}
I have few checkboxes whose values are coming from loop,Here I am validating those checkboxes using reactive form.My validation is atleast one checkboxes should be selected.when I check and uncheck the checkbox validation is working fine,but when my all checkboxes are already preselected and click submit,even though its showing empty message.Is there any solution for it.Here is the code below.
home.component.html
<div>
<p>Form 1</p>
<form [formGroup]="registerForm">
<div *ngFor="let grpdata of statusdata">
<input type="checkbox" formControlName="title" value="{{grpdata.groupid}}" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.title.errors }">{{grpdata.groupname}}<br>
</div>
<div *ngIf="submitted && f.title.errors" class="invalid-feedback">
<div *ngIf="f.title.errors.required">Title is required</div>
</div>
<button type="submit" (click)="getSelectedVal()">Click here</button>
</form>
</div>
<div>
<p>Form 2</p>
<form [formGroup]="editForm">
<input type="textbox" disabled formControlName="edithidden" [(ngModel)]="hello" class="form-control"><br>
<div *ngFor="let grpdata of statusdata">
<input type="checkbox" formControlName="edittitle" [checked]=true value="{{grpdata.groupid}}" class="form-control" [ngClass]="{ 'is-invalid': submitted1 && g.edittitle.errors }">{{grpdata.groupname}}<br>
</div>
<div *ngIf="submitted1 && g.edittitle.errors" class="invalid-feedback">
<div *ngIf="g.edittitle.errors.required">Title is required</div>
</div>
<button type="submit" (click)="editSelectedVal()">Click here</button>
</form>
</div>
home.component.ts
import { Component, OnInit } from '#angular/core';
import { CommonserviceService } from './../utilities/services/commonservice.service';
import { FormBuilder, FormControl, FormGroup, Validators } from '#angular/forms';
declare var $: any;
#Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
submitted = false;
submitted1 = false;
getListData: any;
registerForm: FormGroup;
editForm: FormGroup;
statusdata: any;
constructor(private commonserviceService: CommonserviceService,private formBuilder: FormBuilder)
{
this.registerForm = this.formBuilder.group({
title: [false, Validators.requiredTrue],
});
this.editForm = this.formBuilder.group({
edittitle: [false, Validators.requiredTrue],
edithidden: new FormControl()
});
}
ngOnInit() {
this.statusdata = [{"groupid":1,"groupname":"project1"},{"groupid":2,"groupname":"project2"},{"groupid":3,"groupname":"project3"}];
}
get f() { return this.registerForm.controls; }
get g() { return this.editForm.controls; }
getSelectedVal(){
this.submitted = true;
// stop here if form is invalid
if (this.registerForm.invalid) {
return;
}
console.log('submitted');
}
editSelectedVal(){
this.submitted1 = true;
// stop here if form is invalid
if (this.editForm.invalid) {
return;
}
console.log('submitted edit');
}
}
<input type="checkbox" formControlName="edittitle" [checked]=true...
You shouldn't try to set the value from outside of the form. You never know when it is actually attached. When you want to have the checkbox to be preselected use the form value instead.
this.editForm = this.formBuilder.group({
edittitle: [true, Validators.requiredTrue], // true here, you had false here
edithidden: new FormControl()
});