Angular Object is possibly 'null'. Error at <span *ngIf="checkoutForm.get('emailAddr').hasError('required')">Enter email address</span> - angular11

Hi I am new to Angular 11 can anyone please help me with this error -
This is my code.
checkout.component.html
<h3>Checkout forms - Using Reactive forms</h3>
<div class="container">
<form [formGroup]="checkoutForm" (ngSubmit)="postData();">
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email" name="emailAddressField" formControlName="emailAddr">
<span *ngIf="checkoutForm.get('emailAddr').hasError('required')">Enter email address</span>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Quantity</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password" name="passwordField" formControlName="quantity">
<small id="emailHelp" class="form-text text-muted">Enter Quantity</small>
</div>
<div class="form-check">
<input type="checkbox" class="form-check-input" id="exampleCheck1" name="termsField" formControlName="terms">
<label class="form-check-label" for="exampleCheck1">Agree to Terms</label>
</div>
<br>
<button type="submit" class="btn btn-primary" [disabled]="!checkoutForm.valid">Checkout</button>
</form>
</div>
I am getting error as Error at <span *ngIf="checkoutForm.get('emailAddr').hasError('required')">Enter email address
checkout.component.ts
import { Component, Input, OnInit } from '#angular/core';
import { FormGroup, FormControl, FormBuilder,Validators} from '#angular/forms';
#Component({
selector: 'app-checkout',
templateUrl: './checkout.component.html',
styleUrls: ['./checkout.component.css']
})
export class CheckoutComponent implements OnInit {
checkoutForm:FormGroup;
constructor(private formBuilder:FormBuilder) {
this.checkoutForm = formBuilder.group({
emailAddr: ['',Validators.required],
quantity: ['',Validators.required],
terms: ['',Validators.requiredTrue]
});
}
ngOnInit(): void {
}
postData(){
console.log(this.checkoutForm);
}
}

Instead of using
<span *ngIf="checkoutForm.get('emailAddr').hasError('required')">Enter email address</span>
Try
<span *ngIf="checkoutForm.get('emailAddr')?.hasError('required')">Enter email address</span>
i have tested this code on my computer maybe it will also help you to resolve your compilation error.

You can use *ngIf="cadastroForm.get('username')?.errors">.
You have to use the ?.

Related

Using input tag helper "name" and getting input value empty. ASP.NET MVC (.NET 5)

I have simple form for creating items
<form asp-action="CreateItem" enctype="multipart/form-data">
<div class="form-group">
<label asp-for="#Model.ItemPhoto" class="control-label"></label>
<input type="file" asp-for="#Model.ItemPhoto" name="Photo" class="form-control-file" />
<span asp-validation-for="#Model.ItemPhoto" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="#Model.Name" class="control-label"></label>
<input asp-for="#Model.Name" class="form-control" />
<span asp-validation-for="#Model.Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="#Model.ItemType" class="control-label"></label>
<select asp-for="#Model.ItemType" class="form-control">
#foreach (var itemType in Enum.GetValues(typeof(RandApp.Enums.ItemType)))
{
<option value="#itemType.ToString()">#itemType</option>
}
</select>
<span asp-validation-for="#Model.ItemType" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="#Model.MaterialType" class="control-label"></label>
<select asp-for="#Model.MaterialType" class="form-control">
#foreach (var materialType in Enum.GetValues(typeof(RandApp.Enums.MaterialType)))
{
<option value="#materialType.ToString()">#materialType</option>
}
</select>
<span asp-validation-for="#Model.MaterialType" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="#Model.Color" class="control-label"></label>
<select asp-for="#Model.Color" class="form-control">
#foreach (var color in Enum.GetValues(typeof(RandApp.Enums.ItemColor)))
{
<option value="#color.ToString()">#color</option>
}
</select>
<span asp-validation-for="#Model.Color" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="#Model.Size" class="control-label"></label>
<select asp-for="#Model.Size" class="form-control">
#foreach (var size in Enum.GetValues(typeof(RandApp.Enums.ItemSize)))
{
<option value="#size.ToString()">#size</option>
}
</select>
<span asp-validation-for="#Model.Size" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="#Model.DesignedFor" class="control-label"></label>
<select asp-for="#Model.DesignedFor" class="form-control">
#foreach (var desigendFor in Enum.GetValues(typeof(RandApp.Enums.DesignedFor)))
{
<option value="#desigendFor.ToString()">#desigendFor</option>
}
</select>
<span asp-validation-for="#Model.DesignedFor" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="#Model.Price" class="control-label"></label>
<input asp-for="#Model.Price" class="form-control" />
<span asp-validation-for="#Model.Price" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="#Model.Description" class="control-label"></label>
<textarea asp-for="#Model.Description" class="form-control"></textarea>
<span asp-validation-for="#Model.Description" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
there is its controller
public async Task<IActionResult> CreateItem(Item item, IFormFile Photo)
{
if (ModelState.IsValid)
{
var path = Path.Combine(_webHostEnvironment.WebRootPath, "assets", Photo.FileName);
var stream = new FileStream(path, FileMode.Create);
await Photo.CopyToAsync(stream);
item.ItemPhoto = Photo.FileName;
await _itemRepo.CreateAsync(item);
ViewBag.Item = item;
return RedirectToAction("ReadItems");
}
return View();
}
my goal is to get the path of chosen photo and save it in folder called "assets"(located in "wwwroot" folder).
The problem is that when i fill the fields and submitting the values, i get item.ItemPhoto value null and i can't enter in if statement. (see the photo down below).
[1]: https://i.stack.imgur.com/H2aLt.png
one solution i have found is to remove "enctype="multipart/form-data" from form and "name="Photo" tag helper from input
<form asp-action="CreateItem" enctype="multipart/form-data">
<div class="form-group">
<label asp-for="#Model.ItemPhoto" class="control-label"></label>
<input type="file" asp-for="#Model.ItemPhoto" name="Photo" class="form-control-file" />
<span asp-validation-for="#Model.ItemPhoto" class="text-danger"></span>
</div>
but in this case i can't get the path properly.
what can i do to solve this problem, why am i getting empty value from input?
File and string type cannot be passed together with the same name automatically and cannot achieve this requirement by using just one input. You can set a hidden input for ItemPhoto and use js to set the value when the file changed:
#model Item
<form asp-action="CreateItem" enctype="multipart/form-data">
<div class="form-group">
<label asp-for="#Model.ItemPhoto" class="control-label"></label>
//change here...
<input type="file" name="ItemPhoto" class="form-control-file" onchange="SetValue(this)" />
//add hidden input......
<input asp-for="#Model.ItemPhoto" hidden/>
<span asp-validation-for="#Model.ItemPhoto" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="#Model.Name" class="control-label"></label>
<input asp-for="#Model.Name" class="form-control" />
<span asp-validation-for="#Model.Name" class="text-danger"></span>
</div>
<input type="submit" value="Create"/>
</form>
#section Scripts
{
<script>
function SetValue(input) {
var fileName = input.files[0].name;
//asp-for will generate the id and name
//so you can get the selector by using $("#ItemPhoto")
$("#ItemPhoto").val(fileName);
}
</script>
}
Backend (The name attribute should always match with the parameter/property name):
public async Task<IActionResult> CreateItem(Item item, IFormFile ItemPhoto)
{
//....
return View();
}

I can not insert a record into firestore database using angular 12

There is no error showing when i run ng serve or ng build, but it can't still make a record. I am blown away. Please help me.
I can show you some relevant parts in which i made some changes.
i created a student class in model.ts file, then i created an instance of the class in service class. Afterward, in build component of html file i created the submit() method as shown below
model.ts
export class Students{
id!: string;
matricule!:string;
nom!: string;
prenom!: string;
Quartier!:string;
age!:number
}
student.service.ts
import { AngularFirestoreDocument } from '#angular/fire/compat/firestore';
import { Students } from './model';
#Injectable({
providedIn: 'root'
})
export class StudentService {
constructor() { }
formData: Students = new Students();
}
student.component.ts
import { AngularFirestore } from '#angular/fire/compat/firestore';
import { NgForm } from '#angular/forms';
import { StudentService } from 'src/app/shared/student.service';
#Component({
selector: 'app-student',
templateUrl: './student.component.html',
styleUrls: ['./student.component.scss']
})
export class StudentComponent implements OnInit {
constructor(public service:StudentService, private firestore:AngularFirestore)
{ }
ngOnInit(): void {
this.resetForm();
}
resetForm(form?:NgForm) {
if(form!= null) {
form.resetForm();
this.service.formData = {
id:'',
matricule:'',
nom:'',
prenom:'',
age:0,
Quartier:''
}
}
}
onSubmit(form:NgForm) {
let data = form.value;
this.firestore.collection('students').add(data);
this.resetForm(form);
}
}
student.component.html
<form #form="ngForm" autocomplete="off" (submit)="onSubmit(form)">
<div class="form-group">
<input name="matricule" #matricule="ngModel" [(ngModel)]="service.formData.matricule" class="form-control" placeholder="Matricule" required>
<div *ngIf="matricule.invalid && matricule.touched" class="validation-error">Ce chant est obligatoire</div>
</div>
<div class="form-group">
<input name="nom" #nom="ngModel" [(ngModel)]="service.formData.nom" class="form-control" placeholder="Nom" required>
<div *ngIf="nom.invalid && nom.touched" class="validation-error">Ce chant est obligatoire</div>
</div>
<div class="form-group">
<input name="prenom" #prenom="ngModel" [(ngModel)]="service.formData.prenom" class="form-control" placeholder="Prenom" required>
<div *ngIf="prenom.invalid && prenom.touched" class="validation-error">Ce chant est obligatoire</div>
</div>
<div class="form-group">
<input type="number" name="age" #age="ngModel" [(ngModel)]="service.formData.age" class="form-control" placeholder="Age" required>
<div *ngIf="age.invalid && age.touched" class="validation-error">Ce chant est obligatoire</div>
</div>
<div class="form-group">
<input name="Quartier" #Quartier="ngModel" [(ngModel)]="service.formData.Quartier" class="form-control" placeholder="Quartier" required>
<div *ngIf="Quartier.invalid && Quartier.touched" class="validation-error">Ce chant est obligatoire</div>
</div>
<div class="form-group">
<button type="submit" [disabled]="form.invalid" class="btn btn-lg btn-block btn-info">SUBMIT</button>
</div>
</form>

How to display the title in the center?

This is the output of my code:
I want the "welcome to the site" to be displayed at center of the page, how do i do this?
This is the code of app.component.html here I haved {{title}} templated which will be displayed at the top of the page.
<h4>{{title}}</h4>
<div class="col-sm-10">
<button type="button" class="btn btn-default" (click)="createEmp()">Create Employee</button>
</div>
<div style="margin-top: 60px;">
<div class = "container">
<div *ngIf="add">
<h2>Add Employee:</h2>
<form class="form-horizontal" #empForm="ngForm">
<div class="form-group">
<label class="control-label col-sm-2" for="name">Name:</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="name" minlength="4" [(ngModel)]="model.name" placeholder="Enter Your Name" #name="ngModel" required/>
<div *ngIf="name.invalid && (name.dirty || name.touched)" class="alert alert-danger">
<div *ngIf="name.errors.required">
Name is required.
</div>
<div *ngIf="name.errors.minlength">
Name must be at least 4 characters long.
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="position">Position:</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="position" [(ngModel)]="model.position" placeholder="Enter your position" required />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="salary">Salary:</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="salary" [(ngModel)]="model.salary" placeholder="Enter Salary" required />
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default" (click)="addEmployee()" [disabled]="empForm.invalid">Add Employee</button>
</div>
</div>
</form>
</div>
<div *ngIf="edit">
<h2>Update Employee:</h2>
<form class="form-horizontal">
<div class="form-group">
<label class="control-label col-sm-2" for="name">Name:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="name"
name="name" [(ngModel)]="model2.name" placeholder="Enter Your Name" #name="ngModel" required/>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="position">Position:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="position" name="position" [(ngModel)]="model2.position" placeholder="Enter your position" required/>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="salary">Salary:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="salary" name="salary" [(ngModel)]="model2.salary" placeholder="Enter Salary" required/>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default" (click)="updateEmployee()">update Employee</button>
</div>
</div>
</form>
</div>
<div *ngIf="Show">
<h2>Employee Details</h2>
<table class="table table-bordered">
<thead>
<tr>
<th width=400>Name</th>
<th width=400>Position</th>
<th width=200>Salary</th>
<th width=400>Actions</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let employee of employees; let i=index">
<td>{{employee.name}}</td>
<td>{{employee.position}}</td>
<td>{{employee.salary}}</td>
<td>
<a class="btn btn-success" (click)="editEmployee(i)">Edit</a>
<a class="btn btn-danger" (click)="deleteEmployee(i)">Delete</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
this is the ts file where i added title name here
import {Component, OnInit} from '#angular/core';
import { FormControl, FormGroup , Validators} from '#angular/forms';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
model:any={};
model2:any={};
edit= false;
add=false;
create=true;
Show=false;
myValue;
ngOnInit(){
this.model = new FormGroup({
'name': new FormControl(this.model.name, [
Validators.required,
Validators.minLength(4),
]),
'position': new FormControl(this.model.position),
'salary': new FormControl(this.model.salary, Validators.required)
});
}
title = 'Welcome to the Site';
employees = [{name :"Sunil", position : "Developer", salary : 20000},
{name :"Vamshi", position : "Java Developer", salary : 30000},
{name : "Chethan", position : ".Net Developer", salary : 10000}];
createEmp(){
this.add=true;
this.create=false;
this.Show=false;
this.edit=false;
}
addEmployee()
{
console.log()
this.employees.push(this.model);
this.Show = true;
this.add=false;
this.model = {};
}
deleteEmployee(i){
this.employees.splice(i,1)
this.Show=true;
console.log(i);
}
editEmployee(k){
this.edit = true;
this.Show=false;
this.add=false;
this.model2.name = this.employees[k].name;
this.model2.position = this.employees[k].position;
this.model2.salary = this.employees[k].salary;
this.myValue = k;
}
updateEmployee(){
this.Show=true;
this.edit = false;
let k = this.myValue;
for(let i=0;i<this.employees.length;i++){
if(i==k)
{
this.employees[i]= this.model2;
this.model2 = {};
}
}
}
}
The title must be displayed center at all of the pages tag is not helping for me. Is there another way to do this?
You just need to use the align:center; css for your <h4> tag that has the title value:
h4 {
text-align: center;
}

how to get data by finding all and finding one at the same time

In my project on the user edit page I would like to show the current role,wich i get by findOne byId,but I would also like to get all available roles so that I can choose, roles are in a separate collection, and I dont have a problem when displaying eather one...or all..
<div class="form-group col-lg-12">
<label>Email</label>
<input type="email" class="form-control" id="email" value="{{emails.[0].address}}">
</div>
<div class="form-group col-lg-12">
<label>Password</label>
<input type="password" name="" class="form-control" id="password" value="{{password}}">
</div>
<div class="form-group col-lg-6">
<label>Name</label>
<input type="text" name="" class="form-control" id="firstname" value="{{profile.name}}">
</div>
<div class="col-xs-12"><strong>Current role:</strong>
<label class="radio-inline">
<input type="radio" name="optradio" id="accountRole" value="{{roleName profile.role}}" checked>{{roleName profile.role}}
</label>
</div>
{{/with}}
<div class="col-xs-12">
<form>
<div class="col-xs-12"><strong>Roles:</strong>
{{#each rolesInformation}}
<label class="radio-inline">
<input type="radio" name="optradio" id="accountRole" value="{{_id}}">{{roleName}}
</label>
{{/each}}</div>`
helpers look like this:
Template.editUser2.helpers({
user: () => {
return Meteor.users.findOne({_id:Session.get('id')});
},
playerInformation: () => {
return Players.find().fetch();
},
roleName: (id)=>{
return Roles.findOne({_id:id}).roleName;
},
rolesInformation: () =>{
return Roles.find().fetch();
},
when i run roleName or rolesInformation separateli it works fine...
whet both included i get "roleName not defined"

Unterminated JSX contents

In a meteor app, I am trying to render a login form using React.
import React from 'react';
export default class Login extends React.Component {
render() {
return (
<div class="login-card">
<h1>Log-in</h1><br>
<form>
<input type="text" name="user" placeholder="Username" />
<input type="password" name="pass" placeholder="Password" />
<input type="submit" name="login" class="login login-submit" value="login" />
</form>
<a class="login-help" href="#">Register</a>
</div>
);
}
}
But metor is unable to compile the above jsx file and says .
While processing files with ecmascript (for target web.browser):
client/loginForm.jsx:15:8: Unterminated JSX contents (15:8)
What can be the reason?
You need to close br element, in react always use selft close tags, and also dont use class use className instead
import React from 'react';
export default class Login extends React.Component {
render() {
return (
<div className="login-card">
<h1>Log-in</h1><br/> // Close br
<form>
<input type="text" name="user" placeholder="Username" />
<input type="password" name="pass" placeholder="Password" />
<input type="submit" name="login" className="login login-submit" value="login" />
</form>
<a className="login-help" href="#">Register</a>
</div>
);
}
}
import React from 'react';
export default class Login extends React.Component {
render() {
return (
<div class="login-card">
<h1>Log-in</h1><br></br>
<form>
<input type="text" name="user" placeholder="Username" />
<input type="password" name="pass" placeholder="Password" />
<input type="submit" name="login" class="login login-submit" value="login" />
</form>
<a class="login-help" href="#">Register</a>
</div>
);
}
}
Close the br tag

Resources