I have built a modal component with 1 textfield and a submit button, with a required validator on that specific textfield. It seems the Validator is working, but somehow the validator error message is not shown.
The typescript code for the component:
#Injectable()
export class AddOrganizationComponent implements OnInit {
public addOrganizationFormGroup: FormGroup;
public submittedAddOrganization = false;
modalService: BsModalService;
formModal: BsModalRef;
form = {
class: "modal-dialog-centered modal-sm"
};
constructor(private addOrganizationFormBuilder: FormBuilder,
private injector: Injector) {
}
ngOnInit(): void {
this.enableAddOrganizationForm();
}
public openAddOrganizationModal() {
this.modalService = this.injector.get(BsModalService);
this.formModal = this.modalService.show(AddOrganizationComponent, this.form);
}
public addOrganization() {
this.submittedAddOrganization = false;
if(this.addOrganizationFormGroup.invalid) {
console.log('Yes is invalid ');
} else {
console.log('Adding Organization function!');
}
}
get addOrganizationFormGroupControls() {
return this.addOrganizationFormGroup.controls;
}
public enableAddOrganizationForm() {
this.addOrganizationFormGroup = this.addOrganizationFormBuilder.group({
organizationName: ['', Validators.required]
});
}
}
The HTML code for the component:
<div class="modal-header text-center">
<div class=" modal-body p-0">
<h6 class=" modal-title" id="modal-title-default">
Add Organization
</h6>
<div class=" card bg-secondary border-0 mb-0">
<div class=" card-header bg-transparent pb-3">
<div class=" text-muted text-center mt-2 mb-3">
<small>Type in the name of your new Organization</small>
</div>
</div>
<div class="card-body">
<form role="form" [formGroup]="addOrganizationFormGroup">
<div class="form-group mb-3">
<div class="input-group input-group-alternative">
<input class="form-control" maxlength="20" placeholder="Enter Organization name" type="text" id="organizationNameText" formControlName="organizationName"
[ngClass]="{ 'is-invalid': submittedAddOrganization && addOrganizationFormGroupControls.organizationName.errors }"/>
<div *ngIf="submittedAddOrganization && addOrganizationFormGroupControls.organizationName.errors" style="color:red;font-size:small">
<div *ngIf="addOrganizationFormGroupControls.organizationName.errors.required">A team name is required</div>
</div>
</div>
<div>
<p class="text-muted" *ngIf="addOrganizationFormGroupControls.organizationName.value">{{addOrganizationFormGroupControls.organizationName.value.length}} / 20</p>
</div>
<br/>
</div>
<div class="text-center">
<button type="button" class="btn btn-primary my-4" (click)="addOrganization()">
Add Organization
</button>
</div>
</form>
</div>
</div>
</div>
</div>
I have searched high and low. It seems the validation is working, but the text is not shown, am I missing something or really looking over something small here?
In method called on button click - addOrganization() - you are setting the submittedAddOrganization to false. However, you are expecting it to be true to display the error. Thus: set it to true in button-click handler method.
Related
I have this problem:
Property 'institutionName' does not exist on type 'FormGroup'.
*ngIf="frmStepperControl.institutionName.touched && frmStepper.institutionName.errors?.required">
My ts code
import { Component, OnInit } from '#angular/core';
import { FormBuilder, Validators, AbstractControl, FormGroup, FormControl, FormArray} from '#angular/forms'
#Component({
selector: 'app-forms',
templateUrl: './forms.component.html',
styleUrls: ['./forms.component.scss']
})
export class FormsComponent implements OnInit {
frmValues: object = {};
frmStepper: FormGroup;
public get formArray(): AbstractControl {
// console.log(this.frmStepper.get('steps'));
return this.frmStepper.get('steps');
}
public get frmStepperControl(){
console.log(this.frmStepper.get('steps')['controls'].controls.institutionName);
return this.frmStepper.get('steps')['controls'];
}
constructor(private fb: FormBuilder) {
}
ngOnInit(): void {
this.frmStepper = this.fb.group({
steps: this.fb.array([
this.fb.group({
ieCode: [''],
institutionName: ['', Validators.compose([Validators.required])],
}),
this.fb.group({
telephone1: [null],
}),
])
});
}
submit(): void {
console.log(this.frmStepper.value.steps[0].institutionName);
//this.frmValues = this.frmStepper.value;
}
}
My html code where I'm trying access the touched and errors properties from my institutionName property
<form [formGroup]="frmStepper" (ngSubmit)="submit()">
<timeline-stepper #cdkStepper formArrayName="steps" [linear]="true">
<cdk-step [editable]="false" formGroupName="0" [stepControl]="formArray.get([0])" class="form-cdk">
<div class="row">
<p>Instituição de ensino</p>
<div class="horizontal-divider"></div>
<div class="form-group col-md-6">
<label for="ieCode">Código da IE/IF</label>
<input formControlName="ieCode" type="text" class="form-control" id="ieCode" placeholder="Escreva aqui...">
</div>
<div class="form-group col-md-6">
<label for="institutionName">Nome da Instituição*</label>
<input formControlName="institutionName" type="text" class="form-control" id="institutionName"
placeholder="Escreva aqui..."
required>
<span class="text-danger"
*ngIf="frmStepperControl.institutionName.touched && frmStepper.institutionName.errors?.required">
Nome da Instituição é obrigatória
</span>
</div>
</div>
<footer class="row">
<div class="col-md-6"></div>
<div class="form-group col-md-3">
<button type="button" class="btn btn-primary next" cdkStepperNext>PRÓXIMO</button>
</div>
</footer>
</cdk-step>
<cdk-step #contacts [editable]="false" formGroupName="1" [stepControl]="formArray.get([1])">
<div class="row">
<div class="form-group col-md-6">
<label for="telephone1">Telef.1</label>
<input formControlName="telephone1" type="number" class="form-control" id="telephone1" placeholder="Escreva aqui.">
</div>
</div>
<footer class="row lastRow">
<div class="form-group col-md-3">
<button type="submit" class="btn btn-primary next">PRÓXIMO</button>
</div>
</footer>
</cdk-step>
</timeline-stepper>
</form>
Property 'institutionName' does not exist on type 'FormGroup'.
I'm facing this problem.
In you HTML you have frmStepper.InstitutionName.errors
Should be frmStepperControl.InstitutionName.errors
We are working on the Angular 4 form and set some validations on the input field but the validation is showing when the page load's but we want the validation when the form is submitted or the field is not valid or filled.
Component.html
<div class="headerbutton-group row">
<i class="fa fa-save header-buttons" tooltip ="Save" tabindex="1" (click)="onSave($event)"></i>
<i class="fa fa-close header-buttons" tooltip ="Close" (click)="onCancel($event)"></i>
</div>
<form [formGroup]="editForm" class="col-md-12 ">
<div class="form-group row">
<div class="col-md-6 padding-Mini">
<label class="col-md-12 col-form-label padding-bottom-Mini" for="txtName">Name</label>
<div class="col-md-12">
<input type="text" id="txtName" name="txtName" class="form-control" placeholder="Name" formControlName="name" [class.is-invalid]="!editForm.controls.name.valid" [class.is-valid]="editForm.controls.name.valid" required>
<div class="invalid-feedback" [style.visibility]=
"editForm.controls.name.valid ? 'hidden':'visible'"> Name is required</div>
</div>
</div>
<div class="col-md-6 padding-Mini">
<label class="col-md-12 col-form-label padding-bottom-Mini" for="txtName">Description</label>
<div class="col-md-12">
<input type="text" id="txtDescription" name="txtDescription" class="form-control"
placeholder="Description" formControlName="description">
</div>
</div>
</div>
</form>
Component.ts
#Component({
selector: 'app-edit-form',
templateUrl: './component.html'
})
export class LoginFormComponent implements OnInit {
constructor(fb:FormBuilder) {
public editForm: FormGroup = new FormGroup({
name : new FormControl('', Validators.required),
description : new FormControl(''),
});
}
public onSave(e): void {
if (this.editForm.valid) {
e.preventDefault();
this.save.emit(this.editForm.value);
} else {
this.validateAllFormFields(this.editForm);
}
}
public onCancel(e): void {
e.preventDefault();
this.closeForm();
}
private validateAllFormFields(formGroup: FormGroup) {
Object.keys(formGroup.controls).forEach(field => {
const control = formGroup.get(field);
if (control instanceof FormControl) {
control.markAsTouched({ onlySelf: true });
} else if (control instanceof FormGroup) {
this.validateAllFormFields(control);
}
});
}
}
// Tried this too editForm.controls.name.pristine
We don't know what we are missing. Kindly help us, with useful documents/ Demo's.
try changing this
<div class="invalid-feedback" [style.visibility]="editForm.controls.name.valid ? 'hidden':'visible'">
Name is required
</div>
to this
<div class="invalid-feedback" *ngIf="!editForm.controls.name.valid && editForm.controls.name.touched">
Name is required
</div>
adding a test on "touched" will fix your problem !
I wanted to add new record to my MSSQL database with my Angular SPA, but when I send the form I got nothing but just error 400 - Bad Request. I think it's only SPA fault, because everything is working just fine when I test it with Postman.
My POST body should look like this:
{
"Nazwa": "String",
"Opis": "Another String",
"Ownerusername": "Another String",
"Ends": "1976-07-28"
}
So I made a simple model in my eventcreator.component.ts:
import { Component, OnInit } from '#angular/core';
import { EventService } from '../_services/evncreator.service';
declare let alertify: any ;
#Component({
selector: 'app-eventcreator',
templateUrl: './eventcreator.component.html',
styleUrls: ['./eventcreator.component.css']
})
// declare let alertify;
export class EventcreatorComponent implements OnInit {
model: any = [];
constructor(private evntservice: EventService) {}
ngOnInit() {}
evnCreate() {
// this.model = JSON.parse(this.model);
this.evntservice.eventCreate(this.model).subscribe(
() => {
alertify.success('Utworzono wydarzenie');
},
error => alertify.error('Wystąpił błąd')
);
console.log(this.model);
}
evnAbort() {
window.location.href = '/';
}
}
This script is using evntservice.component.ts, so I want to attach it too:
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { map } from 'rxjs/operators';
import { JwtHelperService } from '#auth0/angular-jwt';
#Injectable({
// dekorator
providedIn: 'root'
})
export class EventService {
constructor(private http: HttpClient) {}
eventCreate(model: any) {
return this.http.post('http://localhost:5000/api/Events', model);
}
}
My eventcreator.component.html is looking like this:
<form #registerForm="ngForm" (ngSubmit)="evnCreate()">
<div class="content p-3 ml-4 mr-4 bg-white">
<h1 class="display-2 text-dark text-center">Kreator wydarzeń</h1>
</div>
<div class="content">
<div class="content ml-4 mr-4 p-3 bg-warning">
<h1 class="ml-2 mt-4 mb-4 text-center">Nazwa wydarzenia:</h1>
<input
class="form-control mt-3 mb-3 p-lg-4 "
[(ngModel)]="model.Nazwa"
name="Nazwa"
required
/>
<div class="text-break"></div>
<h1 class="ml-2 mt-4 mb-4 text-center">Opis wydarzenia:</h1>
<textarea
class="form-control mt-3 mb-3 p-lg-4"
required
[(ngModel)]="model.Opis"
name="Opis"
></textarea>
<div class="text-break"></div>
<h1 class="ml-2 mt-4 mb-4 text-center">Data wydarzenia:</h1>
<input
type="text"
class="form-control"
required
name="Ends"
[(ngModel)]="model.Ends"
/>
<div class="text-break"></div>
<h1 class="ml-2 mt-4 mb-4 text-center">Organizator:</h1>
<input
class="form-control text-success mt-3 mb-3 p-lg-4 "
required
name="Ownerusername"
[(ngModel)]="model.Ownerusername"
/>
<div class="text-center">
<button
type="submit"
class="btn mr-2 btn-success"
(click)="evnCreate()"
>
Dodaj wydarzenie
</button>
<button
type="button"
class="btn ml-2 btn-secondary"
(click)="evnAbort()"
>
Anuluj
</button>
</div>
</div>
</div>
</form>
Also, I want to include output from model and response from network monitor:
[Nazwa: "nlnkizcxczx", Opis: "zcxczxzxczxczcx", Ends: "2020-03-04", Ownerusername: "PanMichal"]
Nazwa: "nlnkizcxczx"
Opis: "zcxczxzxczxczcx"
Ends: "2020-03-04"
Ownerusername: "PanMichal"
Network monitor:
As you said, POST body should look like below object:
{
"Nazwa": "String",
"Opis": "Another String",
"Ownerusername": "Another String",
"Ends": "1976-07-28"
}
but you are sending an array
[
Nazwa: "nlnkizcxczx",
Opis: "zcxczxzxczxczcx",
Ends: "2020-03-04",
Ownerusername: "PanMichal"
]
so you should try with sending object instead of an array.
Hope this help
Fixed!
What I did:
I replaced
model: any = [];
To:
model: any = {};
I'm getting a very strange error after I upgraded to Angular 6.0.9. My template has a select, where there is an opnion with a value of "" and an "Select an Option" label, and the other options are generated by a list that comes from the bank.
So when I need to clear the form I call the formBuilder again. However, when I clean the form, a request occurs to api and consequently a json error, warning that it can not serialize a null value.
During the reset of the form I do not call any method that triggers the API, so I'm not sure what to do.
It is worth mentioning that the application still works, but it presents the user with an error message, since I have an interceptor that receives all errors and prints in a snack bar...
Template:
<select class="form-control" id="selectTipoDocumento" formControlName="tipoDocumento" [compareWith]="equals"
[class.is-valid]="this.docForm.controls['tipoDocumento'].valid &&
(this.docForm.controls['tipoDocumento'].touched || this.docForm.controls['tipoDocumento'].dirty)"
[class.is-invalid]="!this.docForm.controls['tipoDocumento'].valid &&
(this.docForm.controls['tipoDocumento'].touched || this.docForm.controls['tipoDocumento'].dirty)">
<option value="">Selecione um tipo</option>
<option *ngFor="let tipo of tiposDocumento" [ngValue]="tipo">{{tipo?.nome}}</option>
</select>
Component:
export class DocumentoDetalheComponent implements OnInit {
docForm: FormGroup;
tiposDocumento: TipoDocumento[];
documento: Documento = new Documento();
constructor(
private fb: FormBuilder,
private tipoDocumentoService: TipoDocumentoService,
private documentoService: DocumentoService,
private route: ActivatedRoute
) {}
ngOnInit() {
const idRota: string = this.route.snapshot.params["id"];
this.createFormGroup();
this.tipoDocumentoService.findAll().subscribe(
obj => {
this.tiposDocumento = obj;
},
error => { }
).unsubscribe;
if (idRota != null){
this.documentoService.findById(idRota).subscribe(
obj => {
this.documento = obj;
this.docForm.setValue({
tipoDocumento: this.documento.tipoDocumento,
resumo: this.documento.resumo,
observacao: this.documento.observacao
});
},
error => { }
);}
}
onSubmit() {
let docTemp: Documento = this.docForm.value;
this.documento.tipoDocumento = docTemp.tipoDocumento;
this.documento.resumo = docTemp.resumo;
this.documento.observacao = docTemp.observacao;
if (this.documento.id == null) {
this.save(this.documento);
} else {
this.update(this.documento);
}
}
save(documento: Documento) {
this.documentoService
.insert(documento)
.subscribe(response => console.log(response));
}
update(documento: Documento) {
this.documentoService.update(documento).subscribe(response => console.log(response));
}
createFormGroup() {
this.docForm = this.fb.group({
tipoDocumento: ["", [Validators.required]],
resumo: ["",[Validators.required, Validators.minLength(5), Validators.maxLength(60)]],
observacao: ["", [Validators.maxLength(500)]]
});
}
limparForm() {
this.createFormGroup();
}
equals(tp1: TipoDocumento, tp2: TipoDocumento) {
return tp1.id === tp2.id
}
voltar() {}
}
API error:
2018-07-16 10:05:43.186 WARN 4996 --- [ tomcat-http--5] .w.s.m.s.DefaultHandlerExceptionResolver : Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot construct instance of `br.mp.mpce.sge.domain.TipoDocumento` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value (''); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `br.mp.mpce.sge.domain.TipoDocumento` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('')
at [Source: (PushbackInputStream); line: 1, column: 579] (through reference chain: br.mp.mpce.sge.domain.Documento["tipoDocumento"])
I found the solution. The problem was in my formGroup, where I was using ngSubmit, so all buttons in my form were submitting API requests. So, the solution was to remove ngSubmir from the form, as well as manually set, in the event (click), the necessary methods.
<form [formGroup]="docForm" novalidate>
<div class="card">
<div class="card-body">
<div class="form-group row" *ngIf="documento?.id != null">
<div class="form-group col-md-3">
<label for="setor">Nº Protocolo: </label>
</div>
<div class="form-group col-md-6">
{{documento?.codigo}}/{{documento?.ano}}
</div>
</div>
<div class="form-group row" *ngIf="documento?.id != null">
<div class="form-group col-md-3">
<label for="setor">Setor cadastro: </label>
</div>
<div class="form-group col-md-6">
{{documento?.setorCadastro?.nome}}
</div>
</div>
<div class="form-group row">
<div class="form-group col-md-3">
<label for="selectTipoDocumento">Tipo de Documento: </label>
</div>
<div class="form-group col-md-6">
<select class="form-control" id="selectTipoDocumento" formControlName="tipoDocumento" [compareWith]="equals"
[class.is-valid]="this.docForm.controls['tipoDocumento'].valid &&
(this.docForm.controls['tipoDocumento'].touched || this.docForm.controls['tipoDocumento'].dirty)"
[class.is-invalid]="!this.docForm.controls['tipoDocumento'].valid &&
(this.docForm.controls['tipoDocumento'].touched || this.docForm.controls['tipoDocumento'].dirty)">
<option value="">Selecione um tipo</option>
<option *ngFor="let tipo of tiposDocumento" [ngValue]="tipo">{{tipo?.nome}}</option>
</select>
</div>
<div class="form-group col-md-3 invalid-feedback d-block"
*ngIf="!this.docForm.controls['tipoDocumento'].valid && (this.docForm.controls['tipoDocumento'].touched || this.docForm.controls['tipoDocumento'].dirty)">
Tipo dodocumento é obrigatório
</div>
</div>
<div class="form-group row">
<div class="form-group col-md-3">
<label for="inputResumo">Resumo: </label>
</div>
<div class="form-group col-md-6">
<input type="text" class="form-control" id="inputResumo" formControlName="resumo" placeholder="Resumo do documento" maxlength="60"
autocomplete="off"
[class.is-valid]="this.docForm.controls['resumo'].valid && (this.docForm.controls['resumo'].touched || this.docForm.controls['resumo'].dirty)"
[class.is-invalid]="!this.docForm.controls['resumo'].valid && (this.docForm.controls['resumo'].touched || this.docForm.controls['resumo'].dirty)">
</div>
<div class="form-group col-md-3 invalid-feedback d-block"
*ngIf="!this.docForm.controls['resumo'].valid && (this.docForm.controls['resumo'].touched || this.docForm.controls['resumo'].dirty)">
Resumo é obrigatório (5 a 60 caracteres)
</div>
</div>
<div class="form-group row">
<div class="form-group col-md-3">
<label for="inputObservacao">Observação: </label>
</div>
<div class="form-group col-md-6">
<textarea type="text" class="form-control" id="inputObservacao" formControlName="observacao" rows="5">
</textarea>
</div>
</div>
<div class="form-group row">
<div class="form-group col-md-3">
</div>
<div class="form-group col-md-2">
<button class="btn btn-primary btn-block" (click)="limparForm()">Limpar</button>
</div>
<div class="form-group col-md-2">
<button class="btn btn-success btn-block"[disabled]="!docForm.valid" (click)="onSubmit()">Salvar</button>
</div>
<div class="form-group col-md-2">
<a class="btn btn-primary btn-block" [routerLink]="['/']">Voltar</a>
</div>
</div>
</div>
</div>
</form>
I have a main page with a table that when a row is clicked on, it uses #Output to send out that row's data (I've already confirmed the data is being sent properly by using it in another place in the project). I then have a Bootstrap 4 modal that pops up when I click the button on the left below where it says "Data Point Information". What I need to do is take the data from the row that was clicked on, and populate the form inside the modal with it.
Main Page:
Modal:
HTML for the modal:
<div class="modal fade" id="myModal2" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog bodyWidth">
<div class="modal-content wide">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Update Data Point</h4>
</div>
<div class="modal-body">
<form class="form-inline" [formGroup]="updateForm" (ngSubmit)="submitForm(updateForm.value)">
<div class="row">
<div class="form-group" [ngClass]="{'has-error':!updateForm.controls['dataPoint'].valid && updateForm.controls['dataPoint'].touched}">
<label>Data Point:</label>
<input class="form-control special" type="text" [formControl]="updateForm.controls['dataPoint']">
</div>
<div class="form-group move" [ngClass]="{'has-error':!updateForm.controls['ICCP'].valid && updateForm.controls['ICCP'].touched}">
<label >ICCP:</label>
<input type="text" class="form-control special" [formControl]="updateForm.controls['ICCP']">
</div>
<div class="form-group" [ngClass]="{'has-error':!updateForm.controls['startDate'].valid && updateForm.controls['startDate'].touched}">
<label>Start Date:</label>
<input [value]="getDate('start')" class="form-control special" type="text" [formControl]="updateForm.controls['startDate']" style="margin-right: 4px;">
</div>
<div style="display:inline-block">
<ngb-datepicker id="special" *ngIf="startCheck;" [(ngModel)]="startDate" (ngModelChange)="showDatePick(0)" [ngModelOptions]="{standalone: true}"></ngb-datepicker>
</div>
<button type="button" class="btn icon-calendar closest" (click)="showDatePick(0)"></button>
<div class="form-group" [ngClass]="{'has-error':!updateForm.controls['endDate'].valid && updateForm.controls['endDate'].touched}">
<label >End Date:</label>
<input [value]="getDate('end')" class="form-control special" type="text" [formControl]="updateForm.controls['endDate']">
</div>
<div style="display:inline-block">
<ngb-datepicker id="special" *ngIf="endCheck;" [(ngModel)]="endDate" (ngModelChange)="showDatePick(1)" [ngModelOptions]="{standalone: true}"></ngb-datepicker>
</div>
<button type="button" class="btn icon-calendar closer" (click)="showDatePick(1)"></button>
</div>
</form>
</div>
<div class="modal-footer">
*All Fields Are Required. End Date must be after Start Date
<button type="submit" class="btn" [disabled]="!updateForm.valid" data-dismiss="modal">Update</button>
<button type="button" (click)="resetForm()" class="btn" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
Typescript for the modal:
#Component({
selector: 'update-validation',
styleUrls: ['../app.component.css'],
templateUrl: 'update.component.html',
providers: [DatePipe]
})
export class UpdateComponent {
#Input() receivedRow:DataTable;
public dt: NgbDateStruct;
public dt2: NgbDateStruct;
public startCheck: boolean = false;
public endCheck: boolean = false;
updateForm : FormGroup;
constructor(fb: FormBuilder, private datePipe: DatePipe){
this.updateForm = fb.group({
'dataPoint' : [DPS[0].tDataPoint, Validators.required],
'ICCP' : [DPS[0].tICCP, Validators.required],
'startDate' : [DPS[0].tStartDate, Validators.required],
'endDate' : [DPS[0].tEndDate, Validators.required]
}, {validator: this.endDateAfterOrEqualValidator})
}
resetForm(){
location.reload();
//this.updateForm.reset();
}
submitForm(value: any){
console.log(value);
}
public getDate(dateName: string) {
let workingDateName = dateName + 'Date';
let timestamp = this[workingDateName] != null ? new Date(this[workingDateName].year, this[workingDateName].month-1, this[workingDateName].day).getTime() : new Date().getTime();
this.updateForm.controls[dateName + 'Date'].setValue(this.datePipe.transform(timestamp, 'MM/dd/yyyy'));
}
public showDatePick(selector):void {
if(selector === 0) {
this.startCheck = !this.startCheck
} else {
this.endCheck = !this.endCheck;
}
}
endDateAfterOrEqualValidator(formGroup): any {
var startDateTimestamp, endDateTimestamp;
for(var controlName in formGroup.controls) {
if (controlName.indexOf("startDate") !== -1) {
startDateTimestamp = Date.parse(formGroup.controls[controlName].value);
}
if (controlName.indexOf("endDate") !== -1) {
endDateTimestamp = Date.parse(formGroup.controls[controlName].value);
}
}
return (endDateTimestamp < startDateTimestamp) ? { endDateLessThanStartDate: true } : null;
}
}
HTML from the main page that places modal there using it's selector (toSend is of type DataTable which is the data from the row I am sending from the main page's Typescript):
<update-validation [receivedRow]='toSend'></update-validation>
Since I'm using #Output and #Input, I'm not sure why receivedRow in my Typescript is undefined.
The reason is that when your component of modal initialized, there were not any receivedRow. You should control it with *ngIf directive and ngOnChange method like that;
//xyz is just any field on your parent component
//in html
<div *ngIf="xyz">
<update-validation [receivedRow]="xyz"></update-validation>
</div>
//in component of modal
ngOnChanges(){
if(receivedRow){
//do whatever you want
}
}