I try to implement async(isUnique) and sync(cannotContainSpace) validation functions for username field, I want to see "this username already in use alert msg, if textbox value is "yener". sync function works fine but i think ss below can help explain my issue;
Note:canNotContain sync validation func works fine, aafter I added isUnique async function this exception occured..
how can I fix it ?
usernamevalidator.ts
import {FormControl} from '#angular/forms';
export class UsernameValidator{
static isUnique(control:FormControl){
return new Promise((resolve, reject)=>{
setTimeout(function(){
debugger
if(control.value =="yener")
resolve({isUnique:true})
else
resolve(null)
},1000);
});
}
static cannotContainSpace(control:FormControl){
if(control.value.indexOf(' ')>=0)
return { cannotContainSpace:true };
return null;
}
}
postmessage.component.ts
import { Component } from '#angular/core';
import {FormControl,FormGroup,FormBuilder,Validators} from '#angular/forms';
import {UsernameValidator} from '../../validators/usernamevalidator';
#Component({
moduleId:module.id,
selector: 'post-message',
templateUrl: '../../templates/postmessage.component.html'
})
export class PostComponent {
form : FormGroup;
constructor(fb:FormBuilder){
this.form = fb.group({
username:['', Validators.compose([Validators.required, UsernameValidator.cannotContainSpace]),Validators.compose([UsernameValidator.isUnique])],
email:['', Validators.required],
message:['', Validators.required]
});
}
signup(){
console.log(this.form.value);
}
}
here is html template:
<form class="from-horizontal" [formGroup]="form" (ngSubmit)="signup()">
<div class="form-group row">
<label for="username" class="control-label col-md-2">Name:</label>
<div class="col-md-6">
<input type="text" id="username" class="form-control" formControlName="username">
<div *ngIf="form.controls['username'].touched && form.controls['username'].errors">
<div class="alert alert-danger"
*ngIf="form.controls['username'].errors.required">
User name is required.
</div>
<div class="alert alert-danger"
*ngIf="form.controls['username'].errors.cannotContainSpace">
User name can not contain space
</div>
<div class="alert alert-danger" *ngIf="form.controls['username'].errors.isUnique">
This user name already in use.
</div>
</div>
</div>...
it's strange, i though we can use "Validators.compose()" function in form builder initializer as async parameters but angular2 dont agree with me..
I just changed;
username:['', Validators.compose([Validators.required,
UsernameValidator.cannotContainSpace]),Validators.compose([UsernameValidator.isUnique])],
to
username:['', Validators.compose([Validators.required,
UsernameValidator.cannotContainSpace]),UsernameValidator.isUnique],
and it works
EDITED:
also I figured out if you want to use multiple async validators in a component use
Validators.composeAsync()
function.
Related
I am getting the data from the database using an Api which is in the LeaveService. To get the data the method used is applyLeaveGet(id:string) which is in LeaveService. This method provides certain values like the joiningDate from the database.
I am using Angular Material UI with reactive form.
The issue is that even though the leave instance is getting the data, but the in ngOnInt(), the properties are not getting the values.ngOnInt() does get triggred. For example I get the error undefined for joining date.
How can I solve the issue. Thank you for the help
LeaveService : applyLeaveGet(id:string) method
applyLeaveGet(id:string){
return this.http.get<Leave>('https://localhost:44330/api/leave/ApplyLeaveGet/'+ id);
}
ApplyLeave Component
import { HttpClient } from '#angular/common/http';
import { Component, OnInit } from '#angular/core';
import { FormBuilder, FormControl, FormGroup} from '#angular/forms';
import { ActivatedRoute } from '#angular/router';
import { AuthenticationService } from 'src/app/authentication.service';
import { Leave } from '../interfaces/leave';
import { LeaveService } from '../services/leave.service';
#Component({
selector: 'app-add-edit-leave',
templateUrl: './add-edit-leave.component.html',
styleUrls: ['./add-edit-leave.component.css']
})
export class AddEditLeaveComponent implements OnInit {
form: FormGroup;
currentDate = new Date();
minDate: Date;
maxDate: Date;
selectedFile: File = null;
url : any;
leave :Leave;
constructor(private fb: FormBuilder, private http: HttpClient
,private leaveService : LeaveService
,private route : ActivatedRoute
,private authenticationService: AuthenticationService
) {
leaveService.applyLeaveGet(authenticationService.getUserId())
.subscribe(data =>
this.leave = data
);
// Set the minimum to January 1st 20 years in the past and December 31st a year in the future.
const currentYear = new Date().getFullYear();
this.minDate = new Date(currentYear - 20, 0, 1);
this.maxDate = new Date(currentYear + 1, 11, 31);
}
ngOnInit() {
this.form = this.fb.group({
"currentDate": new FormControl(this.currentDate.toISOString().split("T")[0]),
"joiningDate":[''],
"fromDate":[''],
"tillDate":[''],
"leaveType":[''],
"duration":[''],
"reason":[''],
"filePath":['']
});
}
onSelectFile(event: any) {
this.selectedFile = <File>event.target.files[0];
if (event.target.files && event.target.files[0]) {
var reader = new FileReader();
reader.onload = (event: any) => {
this.url = event.target.result;
}
reader.readAsDataURL(event.target.files[0]);
}
else
{
this.url = "";
}
}
onSubmit(){
var userId = this.authenticationService.getUserId();
const formData = new FormData();
formData.append('userId', userId);
formData.append('currentDate', this.form.value.fullName);
formData.append('joiningDate', this.form.value.fullName);
formData.append('fromDate', this.form.value.fullName);
formData.append('tillDate', this.form.value.fullName);
formData.append('leaveType', this.form.value.fullName);
formData.append('duration', this.form.value.fullName);
formData.append('reason', this.form.value.fullName);
formData.append('balanceAnnualLeave', this.form.value.fullName);
formData.append('balanceSickLeave', this.form.value.fullName);
formData.append('balanceAnnualLeave', this.form.value.fullName);
formData.append('File', this.selectedFile);
}
}
this is the html
<p>add-edit-leave works!</p>
<div class="container">
<form class="form-container" [formGroup]="form" (ngSubmit)="onSubmit()">
<mat-card>
<mat-card-header>
<mat-card-title>Apply Leave</mat-card-title>
</mat-card-header>
<mat-card-content>
<div class="row">
<div class="col-md-6">
<mat-form-field class="full-width">
<mat-label>Today's Date</mat-label>
<input formControlName="currentDate" type="date" class="form-control" matInput placeholder="Today's Date" readonly >
</mat-form-field>
</div>
<div class="col-md-6">
<mat-form-field class="full-width">
<mat-label>Joining Date</mat-label>
<input formControlName="joiningDate" type="datetime" class="form-control" matInput placeholder="Joining Date">
</mat-form-field>
</div>
</div>
<!--Date Requested For-->
<div class="row">
<div class="col-md-6">
<mat-form-field class="full-width" appearance="fill">
<mat-label>From Date</mat-label>
<input matInput formControlName="fromDate" [min]="minDate" [max]="maxDate"
[matDatepicker]="picker">
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
</mat-form-field>
</div>
<div class="col-md-6">
<mat-form-field class="full-width" appearance="fill">
<mat-label>Till Date</mat-label>
<input matInput formControlName="tillDate" [min]="minDate" [max]="maxDate"
[matDatepicker]="pickerTillDate">
<mat-datepicker-toggle matSuffix [for]="pickerTillDate"></mat-datepicker-toggle>
<mat-datepicker #pickerTillDate></mat-datepicker>
</mat-form-field>
</div>
</div>
<!--Leave Type Duration(dropdown box)-->
<div class="row">
<div class="col-md-6">
<mat-form-field class="full-width" appearance="fill">
<mat-label>Leave Type</mat-label>
<select formControlName="leaveType" matNativeControl id="mySelectId">
<option value="" disabled selected></option>
<option value="Annual Leave">Annual Leave</option>
<option value="Sick Leave">Sick Leave</option>
</select>
</mat-form-field>
</div>
<div class="col-md-6">
<mat-form-field class="full-width" appearance="fill">
<mat-label>Duration</mat-label>
<select formControlName="duration" matNativeControl id="mySelectId">
<option value="" disabled selected></option>
<option value="Full Day ">Full Day</option>
<option value="First Half Day">First Half Day</option>
<option value="Second Half Day">Second Half Day</option>
</select>
</mat-form-field>
</div>
</div>
<!--Reason-->
<div class="row">
<div class="col-md-12">
<mat-form-field class="full-width">
<mat-label>Reason</mat-label>
<input formControlName="reason" matInput placeholder="Reason">
</mat-form-field>
</div>
</div>
<div class="row">
<div class="col-md-6">
<mat-label>Leave Balacne</mat-label><br>
<ul>
<li>
annualLeaveBalacne: <span>{{leave.balanceAnnualLeave}}</span> <br>
</li>
<li>
sickLeaveBalance: <span>{{leave.balanceSickLeave}}</span>
</li>
</ul>
</div>
</div>
<!--Submit-->
<mat-card-actions>
<button mat-stroked-button type="submit>Basic</button>
</mat-card-actions>
</mat-card-content>
</mat-card>
</form>
</div>
In the current version of your question it does not look like you are any setting values from this.leave in the form in OnInit. From your problem description and the rest of your code I think your problem is the asynchronous call of LeaveService in the constructor. As it it asynchronous code it might not be finished before ngOnInit is called and executed, thus the error messages about undefined values. You have to wait untill the HTTP call is finished before accessing the data.
As you should not perform potentially long running HTTP calls in the constructor, I suggest moving that part in OnInit. Everything that's not long running and asynchronous can be performed in the constructor. Your code could be refactored like this:
constructor(private fb: FormBuilder,
private http: HttpClient,
private leaveService : LeaveService,
private route : ActivatedRoute,
private authenticationService: AuthenticationService
) {
// Set the minimum to January 1st 20 years in the past and December 31st a year in the future.
const currentYear = new Date().getFullYear();
this.minDate = new Date(currentYear - 20, 0, 1);
this.maxDate = new Date(currentYear + 1, 11, 31);
this.form = this.fb.group({
"currentDate": new FormControl(this.currentDate.toISOString().split("T")[0]),
"joiningDate": [''],
"fromDate": [''],
"tillDate": [''],
"leaveType": [''],
"duration": [''],
"reason": [''],
"filePath": ['']
});
}
ngOnInit() {
leaveService.applyLeaveGet(authenticationService.getUserId())
.subscribe(data =>
{
this.leave = data;
// now data is here and can be used to set initial form values, example:
this.form.get('leaveType').setValue(this.leave.Type);
}
);
}
I am trying to display an error message when nothing is typed inside the message input form, but when I load the page I get this error 'TypeError: Cannot read property 'message' of undefined'. I am using react-hook-forms. This is my code down below.
import { Button } from "#material-ui/core";
import { Close } from "#material-ui/icons";
import React from "react";
import { useForm } from "react-hook-form";
import "./SendMail.css";
const SendMail = () => {
const { register, handleSubmit, watch, errors } = useForm();
const onSubmit = (formData) =>{
console.log(formData)
}
return (
<div className="sendMail">
<div className="sendMail__header">
<h3>New Message</h3>
<Close className="sendMail__close" />
</div>
<form onSubmit={handleSubmit(onSubmit)}>
<input name='to' placeholder="To" type="text" {...register('to',{required:true})}/>
<input name="subject" placeholder="Subject" type="text" {...register('subject',{required:true})} />
<input
name="message"
placeholder="Message..."
type="text"
className="sendMail__message"
{...register('message',{required:true})}
/>
{errors.message && <p>To is required!!</p>}
<div className="sendMail__send">
<Button
className="sendMail__send"
variant="contained"
color="primary"
type="submit"
>
Send
</Button>
</div>
</form>
</div>
);
};
export default SendMail;
Since v7 the errors object moved to the formState property, so you need to adjust your destructering:
const { register, handleSubmit, watch, formState: { errors } } = useForm();
I'm trying to set up a drag&drop component to upload multiple files. However, when I attempt to access elements on the DOM with the querySelector method, I end up with null.
I've tried to implement the AfterViewInit class to no avail. Here's my current dart code for the component:
import 'dart:html';
import 'package:dnd/dnd.dart';
import 'package:angular/angular.dart';
#Component(
selector: 'upload',
templateUrl: 'upload.html',
styleUrls: [
'upload.css'
]
)
class Upload implements AfterViewInit {
#override
void ngAfterViewInit() {
// TODO: implement ngOnInit
Draggable d = new Draggable(document.querySelectorAll('.page'), avatarHandler : new AvatarHandler.clone());
var del = document.querySelector('.upload');
print(del); //prints null
Dropzone dropzone = new Dropzone(document.querySelector('.upload')); //throws an error, as it doesn't expect null.
dropzone.onDrop.listen((DropzoneEvent event){
print(event);
});
}
}
Also, my upload.html file is as follows:
<div class="center-me page" uk-grid>
<div class="uk-align-center text-align-center">
<h2 class="text-align-center" >Upload a file</h2>
<div class="upload uk-placeholder uk-text-center">
<span uk-icon="icon: cloud-upload"></span>
<span class="uk-text-middle">Attach binaries by dropping them here or</span>
<div uk-form-custom>
<input type="file" multiple>
<span class="uk-link">selecting one</span>
</div>
</div>
<progress id="progressbar" class="uk-progress" value="0" max="100" hidden></progress>
</div>
</div>
Thanks in advance.
So this looks like it should work. I wouldn't actually suggest doing it this way as it will get any element with an upload class which if you reuse the component will be a lot.
I would suggest using the ViewChild syntax instead
class Upload implements AfterViewInit {
#ViewChild('upload')
void uploadElm(HtmlElement elm) {
Dropzone dropzone = new Dropzone(elm);
dropzone.onDrop.listen((DropzoneEvent event){
print(event);
});
}
}
In the template:
<div class="uk-placeholder uk-text-center" #upload>
That said you shouldn't be getting null from the querySelect, but from the code you have shown I'm not sure why.
employee.component.ts
import { Component, OnInit } from "#angular/core";
import { EmployeeService } from "../Shared/employee.service";
import { NgForm } from "#angular/forms";
#Component({
selector: "app-employe",
templateUrl: "./employe.component.html",
styleUrls: ["./employe.component.css"]
})
export class EmployeComponent implements OnInit {
constructor(private employeeService: EmployeeService) {}
ngOnInit() {
this.resetForm();
}
resetForm(form?: NgForm) {
if (form != null) form.reset();
this.employeeService.SelectedEmployee = {
EmpId: null,
FirstName: "",
LastName: "",
EmpCode: "",
Position: "",
Office: ""
};
}
onSubmit(form ?:NgForm){
this.employeeService.postEmployee(form.value).subscribe(data =>{
this.resetForm(form);
})
}
}
Employee.service.ts
import { Injectable } from "#angular/core";
import { Employee } from "./employee.model";
import {
Http,
Response,
Headers,
RequestOptions,
RequestMethod
} from "#angular/http";
import { Observable } from "rxjs/Observable";
import 'rxjs/add/operator/map';
import "rxjs/add/operator/toPromise";
import 'rxjs/add/operator/catch';
import { map } from 'rxjs/operators';
import 'rxjs/add/operator/map';
#Injectable({
providedIn: "root"
})
export class EmployeeService {
SelectedEmployee: Employee;
constructor(private http: Http) {}
postEmployee(emp : Employee){
var body = JSON.stringify(emp);
var headerOptions = new Headers({'Content-Type':'application/json'});
var requestOptions = new RequestOptions({method : RequestMethod.Post,headers : headerOptions});
return this.http.post('http://localhost:3184/api/Emp',body,requestOptions).map(x => x.json());
}
}
<form class="emp-form" #employeForm="ngForm" >
<input type="hidden" name="EmployeeID" #EmployeeID="ngModel" [(ngModel)]="employeeService.SelectedEmployee.EmpID">
<div class="form-row">
<div class="form-group col-md-6">
<input class="form-control" name="FirstName" #FirstName="ngModel" [(ngModel)]="employeeService.SelectedEmployee.FirstName"
placeholder="First Name" required>
<div class="validation-error" *ngIf="FirstName.invalid && FirstName.touched">This Field is Required.</div>
</div>
<div class="form-group col-md-6">
<input class="form-control" name="LastName" #LastName="ngModel" [(ngModel)]="employeeService.SelectedEmployee.LastName" placeholder="Last Name"
required>
<div class="validation-error" *ngIf="LastName.invalid && LastName.touched">This Field is Required.</div>
</div>
</div>
<div class="form-group">
<input class="form-control" name="Position" #Position="ngModel" [(ngModel)]="employeeService.SelectedEmployee.Position" placeholder="Position">
</div>
<div class="form-row">
<div class="form-group col-md-6">
<input class="form-control" name="EmpCode" #EmpCode="ngModel" [(ngModel)]="employeeService.SelectedEmployee.EmpCode" placeholder="Emp Code">
</div>
<div class="form-group col-md-6">
<input class="form-control" name="Office" #Office="ngModel" [(ngModel)]="employeeService.SelectedEmployee.Office" placeholder="Office">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-8">
<button [disabled]="!employeForm.valid" type="submit" class="btn btn-lg btn-block btn-info" (click)="onSubmit(employeForm)">
<i class="fa fa-floppy-o"></i> Submit</button>
</div>
<div class="form-group col-md-4">
<button type="button" class="btn btn-lg btn-block btn-secondary" (click)="resetForm(employeForm)">
<i class="fa fa-repeat"></i> Reset</button>
</div>
</div>
</form>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Cors;
namespace WebDemo
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.EnableCors(new EnableCorsAttribute("http://localhost:4200", headers: "*", methods: "*"));
// methods:'Access-Control-Request-Method',
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
Here I tried to use Post Data on SqlServer on Button Press and it gives me this error:
Failed to load resource: the server responded with a status of 400 (Bad Request)
localhost/:1 Access to XMLHttpRequest at 'http://localhost:3184/api/Emp' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Please help me to resolve, thanks in advance. I used the reference enter link description here
add origin option before url you need to allow:
config.EnableCors(new EnableCorsAttribute(origins: "http://localhost:4200", headers: "*", methods: "*"));
also you can allow every url like this
config.EnableCors(new EnableCorsAttribute(origins: "*", headers: "*", methods: "*"));
try this
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
400 Error is clear indication of wrong data passing to server. Please check the data what server is expecting and the data you are passing from the Angular side.
im quite new with angular2, but i seem to manage ok for a beginner. However, i'm stuck on some validation issues. i want to validate a component that is not a form field (e.g. input, select e.t.c).
I'm using a bootstrap dropdown which uses an unsorted list.
dropdownButtons.html
<div class="btn-group" dropdown>
<button type="button" class="btn btn-default" dropdownToggle >
{{ selected ? selected : 'Type...'}}
</button>
<ul class="dropdown-menu" dropdownMenu>
<li *ngFor="let value of values;let i = index" (click)="onChange(value)">
{{value.label}}
</li>
</ul>
</div>
dropdownButtons.component.ts
import {Component, EventEmitter, Output, Input, Injectable} from '#angular/core';
import { DROPDOWN_DIRECTIVES } from 'ng2-bootstrap/ng2-bootstrap';
#Component({
selector: 'dropdown-buttons',
template: require('./dropdownButtons.html'),
directives: [DROPDOWN_DIRECTIVES]
})
#Injectable()
export class DropdownButtons {
#Input()
values: DropdownValue[] = [{ "value": "RSS", "label": "RSS" },{ "value": "REST", "label": "REST" }];
#Input()
selected : string;
#Output()
select: EventEmitter<DropdownValue>;
constructor() {
this.select = new EventEmitter();
}
onChange(type) {
this.select.emit(type);
}
}
export class DropdownValue {
value:string;
label:string;
constructor(value:string,label:string) {
this.value = value;
this.label = label;
}
}
My form looks like this.
<form (ngSubmit)="onSubmit()" #refererform="ngForm">
<div class="form-group">
<label for="inputUrl">Url</label>
<input type="text" class="form-control" id="inputUrl" placeholder="Url" required
[(ngModel)]="model.url" name="url">
</div>
<div class="form-group">
<dropdown-buttons [(selected)]="model.type" (select)="onSelect($event)" ></dropdown-buttons>
</div>
<div class="form-group" ng-show="showDetails" *ngIf="isShown()">
<label for="header">Header</label>
<textarea placeholder="Default Input" class="form-control" id="header"
[(ngModel)]="model.header" name="header"></textarea>
</div>
<div class="form-group" ng-show="showDetails" *ngIf="isShown()">
<label for="payload">Payload</label>
<textarea placeholder="Default Input" class="form-control" id="payload"
[(ngModel)]="model.payload" name="payload"></textarea>
</div>
<button type="submit" class="btn btn-danger" >Submit</button>
</form>
I tried to use ngModel (using required in the tags) and the FormGroup option, where i define some formcontrols. It works fine with form controls, but i can't seem to figure out how i validate non form components, is it even possible?
thanks in advance.