but I got this error,
Object is possibly 'null
<span *ngIf="name.errors.minlength">You must enter atleast 3 characters
why my error object is always null,minlength is not store in my error object what is the reason for that?
My hero.ts file is,
export class Hero {
constructor(
public id: number,
public name: string,
public email: string
) { }
}
My formone.component.ts file is,
import { Component, OnInit } from '#angular/core';
import {NgForm} from "#angular/forms";
import {Hero} from "../../hero"
#Component({
selector: 'app-formone',
templateUrl: './formone.component.html',
styleUrls: ['./formone.component.css']
})
export class FormoneComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
model = new Hero(1, 'chamara','chamara#gmail.com');
submitted = false;
onSubmit() { this.submitted = true; }
get diagnostic() { return JSON.stringify(this.model); }
}
My formone.component.html file is,
<div class="container mt-3">
<div class="row">
<div class="col-md-2">
</div>
<div class="col-md-8">
<h4>Template Driven Forms</h4>
<form #formone="ngForm" (ngSubmit)="onSubmit()">
{{diagnostic}}
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name"
required
[(ngModel)]="model.name" name="name" #name="ngModel" minlength="3" #x>
</div>
<div *ngIf="!name.valid" class="alert alert-danger" >
<span *ngIf="name.errors.minlength">You must enter atleast 3 characters</span>
<span *ngIf="name.errors.required">This field required</span>
</div>
<div class="form-group">
<label for="alterEgo">Email</label>
<input type="email" class="form-control" id="alterEgo"
[(ngModel)]="model.email" name="alterEgo">
</div>
<br>
<button type="submit" class="btn btn-primary" [disabled]="!formone.form.valid">Submit</button>
</form>
</div>
<div class="col-md-2">
</div>
</div>
</div>
Plz help me to fix this,
Your Approach seems to be fine (at least for me), might you need to take care of few things
Remove extra #X from input code (this is causing issue by misleading error checking) and try to add name?.errors?.minlength just cross check name exists while checking errors.
<input type="text" class="form-control" id="name" required
[(ngModel)]="model.name" name="name" #name="ngModel" minlength="3">
<span *ngIf="name?.errors?.minlength">You must enter atleast 3 characters</span>
You can check more about template driven error handling here:
https://medium.com/swlh/form-validation-with-angular-template-driven-forms-8e0756cbec5
Happy Coding.. :)
Related
I need your help!I am newbie in Angular Reactive Forms and I am trying to make simple form with validation using Angular's Reactive Forms. But I get an error in this part of my code (ngIf directive, property 'invalid'):
<div class="container">
<form class="card" [formGroup]="form" (ngSubmit)="submit()">
<h1>Angular Forms</h1>
<div class="form-control">
<label>Email</label>
<input type="text" placeholder="Email" formControlName="email">
<div
*ngIf="form.get('email').invalid"
class="validation">
</div>
</div>
<div class="form-control">
<label>Пароль</label>
<input type="password" placeholder="Пароль" formControlName="password">
<div class="validation"></div>
</div>
<div class="card">
<h2>Адрес</h2>
<div class="form-control">
<label>Страна</label>
<select>
<option value="ru">Россия</option>
<option value="ua">Украина</option>
<option value="by">Беларусь</option>
</select>
</div>
<div class="form-control">
<input type="text">
</div>
<button class="btn" type="button">Выбрать столицу</button>
</div>
<div class="card">
<h2>Ваши навыки</h2>
<button class="btn" type="button">Добавить умение</button>
<div class="form-control">
<label></label>
<input type="text">
</div>
</div>
<button class="btn" type="submit" [disabled]="form.invalid">Отправить</button>
</form>
</div>
TypeScript code:
import { Component, OnInit } from '#angular/core';
import { FormControl, FormGroup, Validators } from '#angular/forms';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.less']
})
export class AppComponent implements OnInit {
title = 'forms';
form!: FormGroup;
ngOnInit() {
this.form = new FormGroup({
email: new FormControl('',
[Validators.email,
Validators.required]),
password: new FormControl(null,
[Validators.required,
Validators.minLength(8)])
})
}
submit() {
console.log('Form submitted', this.form);
const formData = { ...this.form.value };
console.log('Form Data:', formData);
}
}
I use Angular 12 and I followed guide on Udemy, so this is very strange, because my mentor's code works correct. I created FromGroup and FormControls, gave them names, so I am really confused about this error. Do you have any ideas how can I fix it?
The Object is possibly 'null' error can happen due to strict type checking and can be solved in 2 ways:
Either assert that you are absolutely sure that can never be null, by using the ! (not null assertion operator)
Use the ? (optional chaining operator) to stop an eventual error from happening in case the object is indeed null
So you can replace the if statement with form.get('email')?.invalid and it should work. A similar question has been asked here.
I try to pass array values from a .ts file to a html file in a Angular Project.
The HTML file is:
<body>
<section id="login" class="d-flex justify-content-center flex-column align-items-center">
<form>
<div class="form-group">
<label>Firmware</label>
<input #firmware class="form-control" type="text" value= {{firmware}} readonly>
</div>
<div class="form-group">
<label>Bootloader</label>
<input #bootloader class="form-control" type="text" value= {{bootloader}} readonly>
</div>
</form>
</section>
</body>
and the .ts file is:
import { Component, OnInit } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { Router, ActivatedRoute, ParamMap } from '#angular/router';
#Component({
selector: 'app-dual',
templateUrl: './dual.component.html',
styleUrls: ['./dual.component.scss']
})
export class DualComponent implements OnInit {
title = "";
constructor(private router: Router, private httpClient : HttpClient) { }
ngOnInit(): void {
var resultArray:number[] = [235,23]
var firmware = resultArray[0];
var bootloader = resultArray[1];
console.log("firmware",firmware);
console.log("bootloader",bootloader);
}
}
If i show the values via console.log they are shown right but if i try to show them in the HTML file the value in the textbox is "[object HTMLInputElement]"
Note: Im new in Angular and try to learn :)
Any tips?
Thank you!
Solution:
HTML:
<div class="form-group">
<label>Firmware</label>
<input class="form-control" type="text" value= {{firmware}} readonly>
</div>
<div class="form-group">
<label>Bootloader</label>
<input class="form-control" type="text" value= {{bootloader}} readonly>
</div>
TypeScript:
var resultArray:number[] = [235,23]
this.firmware = resultArray[0].toString();
this.bootloader = resultArray[1].toString();
console.log("firmware",this.firmware);
console.log("bootloader",this.bootloader);
I deleted my old answer, because I totally missed what was wrong. When you do this:
<input #firmware class="form-control" type="text" value= {{firmware}} readonly>
The #firmware creates a new local variable named firmware, which is equal to the HTML element it's contained in. It's that new local variable that is being displayed inside the curly braces, not the variable firmware which is defined in your DualComponent class.
Make sure you don't duplicate variable names like this, and the problem will go away.
I want to use ngModel, but I have a problem.
This code is not running and it gives me an error.
This is my code:
contact-form.component.html:
<div class="container">
<form>
<div class="form-group">
<label for="firstName">First name</label>
<input ngModel #firstName="firstName" (change)="log(firstName)" id="firstName" type="text" class="form-control"/>
</div>
<div class="form-group">
<label for="comment">comment</label>
<textarea id="comment" rows="3" class="form-control"></textarea>
</div>
<button class="btn btn-primary">Enter</button>
</form>
</div>
contact-form.component.ts:
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-contact-form',
templateUrl: './contact-form.component.html',
styleUrls: ['./contact-form.component.css']
})
export class ContactFormComponent implements OnInit {
constructor() { }
ngOnInit() {
}
log(f) {
console.log(f);
}
}
and this error display in console:
Error: Template parse errors:
There is no directive with "exportAs" set to "firstName" (" <div class="form-group">
<label for="firstName">First name</label>
<input ngModel [ERROR ->]#firstName="firstName" (change)="log(firstName)" id="firstName" type="text" class="form-control"/>
"): ng:///AppModule/ContactFormComponent.html#4:23
What can I do?
modify your input tag in the form like the following :
<input #firstName="ngModel" (change)="log(firstName)"
type="text" class="form-control"/>
Note: if you you want to have Two-way data binding ( [(ngModel)]="propName" ):
<input #firstName="ngModel" (change)="log(firstName)" [(ngModel)]="firstName"
type="text" class="form-control"/>
You can try this:
<div class="form-group">
<label for="firstName">First name</label>
<input [(ngModel)]="firstName" #firstName (change)="log(firstName)" id="firstName" type="text" class="form-control"/>
</div>
for your input tag use this. this will breaking down Two-Way data binding.
<input #firstName (change)="log(firstName)" type="text">
- and to display its content use it as interpolation syntax in your template.
{{firstName.value}}
- after you done text input press enter and results will be in interpolation.
Second way of doing this is like..
in this case you need to define your property name in your component class too.
private firstName;
and in your template file
<input [ngModel]="firstName" (ngModelChange)="firstName = $event" >
{{ firstName }}
make sure you import FormsModule in main app module of your project.
import { FormsModule } from '#angular/forms';
If you want to access template reference variable in your component.ts file then your have to use #ViewChild () directives. and result of this available only in ngAfterViewInit() life cycle method.
#ViewChild ('firstName', { static: false} ) inputRefElm : ElementRef;
ngAfterViewInit(){
console.log(this.inputRefElm.nativeElement.value);
}
I have a FormGroup which has three FormControl fields and one FormArray fields as shown in the figure below. The requirement is to take the manager name from user and once add button is pressed, manager details should be displayed in table. In table a remove button is provided, when remove button is pressed manager should be removed form the table and list. When the form is submitted list of managers should be saved. Everything works fine except formArray logic.
I tried to find a solution to this online (followed various links:- https://alligator.io/angular/reactive-forms-formarray-dynamic-fields/,
Angular 4 Form FormArray Add a Button to add or delete a form input row), but did not helped much. There is not much material on how to store formArray in formGroup. Please suggest.
Below is my code, please have a look:-
1. manager-create-modal.component.html
<div>
<form [formGroup]="createForm" (ngSubmit)="onFormCreation()">
<div class="row">
<div class="column">
<div class="form-inline">
<div class="form-group">
<label for="remote_access_method">Remote Access Method: <font color="orange"> *</font> </label>
<input type="text" size='38' class="form-control" formControlName="remote_access_method" >
</div>
</div>
<br>
<div class="form-inline">
<div class="form-group">
<label for="status">Current Status: <font color="orange"> *</font> </label>
<input type="text" size='38' class="form-control" formControlName="status">
</div>
</div>
<br>
<div class="form-inline">
<div class="form-group">
<label for="secregid">Registration ID:<font color="orange"> *</font> </label>
<input type="text" size='38' class="form-control" formControlName="secregid">
</div>
</div>
<br><br>
<div class="form-inline">
<div class="form-group">
<br><br>
<div formArrayName="manager_formArray">
Enter name: <input type="text" class="form-control" formControlName="MgrName" size='50' >
<button type="button" class="btn btn-primary btn-sm" (click)="addPM()">Add</button>
<br><br>
<table class="table table-hover">
<tr><th>#</th><th>Manager Name</th><th>Remove</th></tr>
<tr *ngFor="let pm of createForm.get('manager_formArray').value; let id = index">
<td>{{id+1}}</td>
<td>{{pm.MgrName}}</td>
<td>
<span class="table-remove">
<button type="button" class="btn btn-primary btn-sm" (click)="removeMgr(id)">Remove</button>
</span>
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
<br>
</div>
<br><br>
<div class="form-group">
<button class="btn btn-primary">Submit</button>
</div>
</form>
</div>
2. manager-create-modal.component.ts
import { Component, OnInit } from '#angular/core';
import { FormGroup, FormBuilder, FormArray, FormControl, Validators } from '#angular/forms';
#Component({
selector: 'app-manager-create-modal',
templateUrl: './manager-create-modal.component.html',
styleUrls: ['./manager-create-modal.component.css']
})
export class ManagerCreateModalComponent implements OnInit {
createForm: FormGroup;
manager_formArray: FormArray;
remote_access_method: FormControl;
status: FormControl;
secregid: FormControl;
constructor(private formBuilder: FormBuilder) { }
createFormControls(){
this.remote_access_method = new FormControl('');
this.status = new FormControl('');
this.secregid = new FormControl('');
this.manager_formArray = new FormArray([ this.createItem() ]);
}
createItem(): FormGroup {
return this.formBuilder.group({
MgrName: ''
});
}
createFormVariables(){
this.createForm = new FormGroup({
remote_access_method : this.remote_access_method,
status : this.status,
secregid : this.secregid,
manager_formArray: this.manager_formArray,
})
}
ngOnInit() {
this.createFormControls();
this.createFormVariables();
}
addPM(mgr: any): void {
console.log("inside addPM");
this.manager_formArray.push(this.formBuilder.group({MgrName:''}));
console.log("list after addition:"+this.manager_formArray.value);
for(let i = 0; i < this.manager_formArray.length; i++) {
console.log(this.manager_formArray.at(i).value);
}
}
get managerFormArray() {
return this.manager_formArray.get('MgrName') as FormArray;
}
onFormCreation(){
console.log("success")
}
}
The manager name is not displayed in the table and I keep on getting below error:-
ERROR Error: Cannot find control with path: 'manager_formArray ->
MgrName' at _throwError (forms.js:1731) at setUpControl
(forms.js:1639) at
FormGroupDirective.push../node_modules/#angular/forms/fesm5/forms.js.FormGroupDirective.addControl
(forms.js:4456) at
FormControlName.push../node_modules/#angular/forms/fesm5/forms.js.FormControlName._setUpControl
(forms.js:4961) at
FormControlName.push../node_modules/#angular/forms/fesm5/forms.js.FormControlName.ngOnChanges
(forms.js:4911) at checkAndUpdateDirectiveInline (core.js:9031)
at checkAndUpdateNodeInline (core.js:10299) at
checkAndUpdateNode (core.js:10261) at debugCheckAndUpdateNode
(core.js:10894) at debugCheckDirectivesFn (core.js:10854) inside
addPM manager-create-modal.component.ts:50 list after
addition:[object Object],[object Object]
manager-create-modal.component.ts:53 {MgrName: ""}
manager-create-modal.component.ts:53 {MgrName: ""}
I even don't understand why elements are not getting added to manager_formArray. Please help me out.
You have a few issues. First of all, it is better to move the Input which adds more FormGroups to your FormArray outside of the <div formArrayName="manager_formArray">- element. I created a new FormControl this.mgrNameInput = new FormControl(''); for this reason (see StackBlitz for more details).
You also need to add the message to the new entry when you press the Add-button, calling the addPM()-method:
addPM(){ // removed the argument, using the controller inside the method instead.
this.manager_formArray.push(this.formBuilder.group({MgrName:this.mgrNameInput.value}));
this.mgrNameInput.reset(); // reset the input field.
}
I also added the remove-method when removing an entry.
removeMgr(index: number){
this.manager_formArray.removeAt(index);
}
Please check the StackBlitz for the complete example
I having trouble on this small project.
I want to make on my html two inputs and they have to filter some data from database. I manged to make one filter (it works) but I dont know how to make second filter. (Im sorry for not using english language in my files and I hope it doesnt bother you).
Here is what i got :
html file
<div class="container">
<form class="navbar-form navbar-left" role="search">
<div class="form-group">
<input type="text" class="form-control" placeholder="Broj Kreveta" [(ngModel)]="broj_kreveta">
<input type="text" class="form-control" placeholder="Broj Kvadrata" [(ngModel)]="broj_kvadrata">
</div>
</form>
<div class="col-lg-12">
<br/>Rooms<br/> <br/>
<div *ngFor="#soba of sobe | SearchPipe:broj_kreveta">
ID room: {{soba.id}}
<br/>
Category: {{soba.kategorija}}
<br/>
Room number: {{soba.broj_sobe}}
<br/>
Number of beds: {{soba.broj_kreveta}}
<br/>
sqm: {{soba.broj_kvadrata}}
<br/><br/>
</div>
</div>
</div>
search.ts
import {Pipe} from 'angular2/core';
#Pipe({
name: 'SearchPipe'
})
export class SearchPipe {
transform (value, [queryString]) {
if (value == null) {
return null;
}
console.log('transform');
return value.filter(item=>item.broj_kreveta.toLowerCase().indexOf(queryString.toLowerCase()) !== -1);
}
}
You can have booth parameters in your pipe:
{{ myData | myPipe: arg1:arg2:arg3... }}
and the pipe definition:
export class MyPipe implements PipeTransform {
transform(value:any, arg1:any, arg2:any, arg3:any):any {
}