In Angular-14 I have this code:
component.ts:
constructor(
private fb: FormBuilder,
private employeeService: EmployeeService,
private bsModalRef: BsModalRef,
private modalService: BsModalService
) {
}
ngOnInit(): void {
}
onSearch() {
this.accountValue = this.createForm.value.accountNumber;
if (this.accountValue !== undefined) {
if (this.accountValue.length === 6) {
this.employeeService.getEmployeeRecords(this.accountValue).subscribe({
next: (res: any) => {
this.allEmployeeDetail = res;
console.log(this.allEmployeeDetail);
this.isLoading = false;
},
error: (error) => {
this.isLoading = false;
}
})
}
}
}
component.html:
<div >
<label for="employeeCode">Employee Code<span style="color:red;">*</span></label>
<input
type="text"
formControlName='employeeCode'
id="employeeCoder"
(input)="onSearch()"
placeholder="employeeCode">
</div>
<label for="employeeName"></label>
console.log(this.allEmployeeDetail) gives as JSON response:
{
"EmployeeCode": "KKT001",
"EmployeeName": "AGBOR PTOLEMY"
}
employeeCode is 6 characters.
What I want to achieve is that when user enters the employeeCode into the text input, as soon as it's 6 characters, the employeeName of that particular employeeCode parameter should be displayed on the label employeeName. If it is not correct, it should display invalid.
How do I achieve this?
Thanks
CodePudding user response:
Just use interpolation
to show the value when its valid like shown below!
component.css
.invalid {
background-color: red;
}
component.ts:
employeeName: string = 'invalid'; // <- changed here
constructor(
private fb: FormBuilder,
private employeeService: EmployeeService,
private bsModalRef: BsModalRef,
private modalService: BsModalService
) {
}
ngOnInit(): void {
}
onSearch() {
this.employeeName = 'invalid'; // <- changed here
this.accountValue = this.createForm.value.accountNumber;
if (this.accountValue !== undefined) {
if (this.accountValue.length === 6) {
this.employeeService.getEmployeeRecords(this.accountValue).subscribe({
next: (res: any) => {
this.allEmployeeDetail = res;
this.employeeName = (this.allEmployeeDetail && this.allEmployeeDetail.EmployeeName) || 'invalid'; // <- changed here
console.log(this.allEmployeeDetail);
this.isLoading = false;
},
error: (error) => {
this.isLoading = false;
}
})
}
}
}
component.html:
<div >
<label for="employeeCode">Employee Code<span style="color:red;">*</span></label>
<input
type="text"
formControlName='employeeCode'
id="employeeCoder"
(input)="onSearch()"
placeholder="employeeCode">
</div>
<label for="employeeName" [ngClass]="{'invalid' : employeeName === 'invalid'}" *ngIf="createForm.value.accountNumber">employeeName</label> <!-- changed here -->