Send data from child to parent component - javascript

I have a button on my child component that should send information to its parent component but this button is not sending this information. I'm probably missing something but I still didn't notice it.
Here's the code from the button inside my child component (there are two buttons: selectPessoaJuridica and selectPessoaFisica:
import { Component, Input, Output, EventEmitter} from '#angular/core';
import { FormBuilder, FormGroup, Validators, FormArray, FormsModule, ReactiveFormsModule} from '#angular/forms';
import {FinalizaDisputaService} from '../services/finaliza-disputa.service';
import {FinalizaDisputaComponent} from './finaliza-disputa.component'
#Component({
moduleId: module.id,
selector: 'titular',
templateUrl: 'dados-titular.component.html'
})
export class TitularComponent {
// we will pass in address from App component
#Input('group')
public titularForm: FormGroup;
#Input() submitted:any;
#Input() indexNumber:any;
#Output() modelChanged = new EventEmitter<boolean>();
public isJuridica = false;
classe = {
pessoa_fisica: 'selected',
pessoa_juridica: ''
};
constructor(private _fb: FormBuilder, private finalizaAcordo:FinalizaDisputaService) {}
selectPessoaFisica(e:boolean){
e = false;
this.classe.pessoa_fisica = "selected";
this.isJuridica = false;
this.classe.pessoa_juridica = "";
this.modelChanged.emit(e)
}
selectPessoaJuridica(e:boolean){
e = true;
this.classe.pessoa_fisica = "";
this.classe.pessoa_juridica = "selected";
this.isJuridica = true;
console.log("ativou", e)
this.modelChanged.emit(e);
}
}
So, what this should do is notify the parent that e is now false.
This is the html from parent component:
<titular (modelChanged)="recebeValidators($event)" [indexNumber]="indice" [submitted]="submitted" [group]="formDadosBancarios.controls.dados_titular.controls[i]"></titular>
And this is the code from parent component where I should receive the value from e (recebeValidators ):
import { Component, OnChanges, OnInit, Input } from '#angular/core';
import { Http } from '#angular/http';
import { FormBuilder, FormGroup, Validators, FormArray, FormsModule, ReactiveFormsModule, AbstractControl, ValidatorFn } from '#angular/forms';
import { FinalizaDisputaService } from '../services/finaliza-disputa.service';
import {DisputaService} from '../../disputas/services/disputas.service';
import { dadosAcordo } from '../model/dados-acordo.interface';
import { TitularComponent } from './dados-titular.component';
import {Routes, RouterModule, Router, ActivatedRoute} from '#angular/router';
#Component({
moduleId: module.id,
selector: 'detalhes',
templateUrl: `finaliza-disputa.component.html`,
providers: [FinalizaDisputaService]
})
export class FinalizaDisputaComponent implements OnInit {
public dados: dadosAcordo;
disputa:any;
public formDadosBancarios: FormGroup;
public submitted: boolean;
public events: any[] = [];
public servError: any;
public indice = 0;
public loading = false;
soma = 0;
public servSuccess: any;
#Input() e:boolean;
cpf_REGEXP = /^\d+$/;
constructor(private _fb: FormBuilder, private service:DisputaService, private finalizaAcordo: FinalizaDisputaService,
private route:ActivatedRoute, private router:Router) {}
ngOnInit() {
this.route.params.subscribe(params => {
let id = params['id'];
this.service
.buscaPorId(id)
.subscribe(disputa => {
this.disputa = disputa;
console.log(disputa.campanha);
console.log(this.disputa.propostas_realizadas);
},
erro => console.log(erro));
})
this.formDadosBancarios = this._fb.group({
id: [''],
termos_condicoes: [false, Validators.requiredTrue],
dados_titular: this._fb.array([
this.initTitular()
])
})
}
/**
* initTitular- Inicializa o grupo de formulário dinâmico e suas validações
* #returns ''
*/
initTitular() {
return this._fb.group({
titular: ['', [<any>Validators.required, <any>Validators.minLength(3)]],
cnpj: [''],
cpf: ['', <any>Validators.required],
data_nasc: ['', <any>Validators.required],
agencia: ['', <any>Validators.required],
banco: ['', <any>Validators.required],
conta: ['', <any>Validators.required],
tipo: ['', <any>Validators.required],
pessoa_juridica: [false],
valor_deposito: ['']
})
}
// this is where I receive e
recebeValidators(model: dadosAcordo, e: any) {
console.log("test", e);
const array = <FormArray>this.formDadosBancarios.get('dados_titular');
const cpf = array.at(this.indice).get("cpf");
const cnpj = array.at(this.indice).get('cnpj');
const data_nasc = array.at(this.indice).get('data_nasc');
const cpfCtrl: AbstractControl = this.formDadosBancarios.get(['dados_titular', this.indice, 'cpf']);
const pessoa_juridicaCtrl: AbstractControl = this.formDadosBancarios.get(['dados_titular', this.indice, 'pessoa_juridica'])
const cnpjCtrl: AbstractControl = this.formDadosBancarios.get(['dados_titular', this.indice, 'cnpj']);
const data_nascCtrl: AbstractControl = this.formDadosBancarios.get(['dados_titular', this.indice, 'data_nasc']);
const reqValidators: ValidatorFn[] = [Validators.required, Validators.pattern(this.cpf_REGEXP)];
if (e == true) {
data_nascCtrl.clearValidators();
cpfCtrl.clearValidators();
cnpjCtrl.setValidators(reqValidators);
}else{
cnpjCtrl.clearValidators();
cpfCtrl.setValidators(reqValidators);
data_nascCtrl.setValidators(reqValidators);
}
data_nascCtrl.updateValueAndValidity();
cpfCtrl.updateValueAndValidity();
cnpjCtrl.updateValueAndValidity();
}
But instead of printing false it is printing undefined. Can someone help me? thanks

It seems you're shadowing a class attribute with the function parameter "e" in the "recebeValidators" function.
The code:
console.log("test", this.e);
should actually be:
console.log("test", e);
To rule out the possibility of a possible casting error in the EventEmitter, try not reusing the parameter function. Example:
selectPessoaFisica(e:any) {
e = false;
this.modelChanged.emit(e)
}
could be rewritten as:
selectPessoaFisica() {
this.modelChanged.emit(false);
}
There's also an extra parameter in the receiving function:
This:
recebeValidators(model: dadosAcordo, e: boolean) {
Should be:
recebeValidators(e: boolean) {

You should type casting it
#Output() modelChanged = new EventEmitter<boolean>();
Also you are referring a wrong variable and you should be passing only one argument as it is in the parent component and remove the this keyword
recebeValidators(e: boolean) {
console.log("test", e);
}

Related

Angular 8.3.15 custom validator with parameter not working as expected

I'm having some trouble getting a custom validator working. I have other custom and non-custom validators working, but this one that I am passing a parameter to does not work as expected. Within the validator, it is recognizing that the validation code is working, but when looking at the form within field-validation-error, it is returning that the form is valid. Any help would be appreciated, thanks!
Within password.component.ts
this.passwordFormGroup = new FormGroup({
hintQuestionFormControl1: new FormControl(this.currentQuestions[0], Validators.required),
hintAnsFormControl1: new FormControl(this.currentAnswers[0], [Validators.required, EditAccountValidators.checkQuestionsDontContainAnswer('hintQuestionFormControl1')]),
});
Within edditAccountValidators.ts
export class EditAccountValidators {
public static checkQuestionsDontContainAnswer(correspondingQuestion: string): ValidatorFn {
return (control: FormControl) => {
if (control.parent) {
const question = control.parent.get(correspondingQuestion).value;
const answer = control.value;
if (question && answer) {
question.split(" ").forEach(function (wordInQuestion) {
answer.split(" ").forEach(function (wordInAnswer) {
if (wordInQuestion.toLowerCase().includes(wordInAnswer.toLowerCase())) {
console.log('same');
return {answerDoesntContainQuestion : true};
}
});
});
}
}
return null;
}
}
Within field-validation-error.component.ts
import {Component, Input, OnInit} from '#angular/core';
#Component({
selector: 'field-validation-error',
templateUrl: './field-validation-error.component.html',
styleUrls: ['./field-validation-error.component.css']
})
export class FieldValidationErrorComponent implements OnInit {
#Input() validatorName: string;
#Input() form: any;
errorMessage: string;
displayError: boolean;
ngOnInit(): void {
this.errorMessage = this.getValidatorErrorMessage();
this.form.valueChanges.subscribe(() => {
this.displayError = this.form.hasError(this.validatorName);
console.log(this.form);
});
}
private getValidatorErrorMessage() {
return this.validatorName;
}
}
calling Within password.component.html
<field-validation-error
[form]="passwordFormGroup.get('hintAnsFormControl1')"
[validatorName]="'answerDoesntContainQuestion'">
</field-validation-error>

How call async validator function on blur in angular reactive form builder?

My async validation function call on every keyup event. How to call async function on blue event.
Registration Component Code::
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
import { FormBuilder, FormGroup, Validators } from '#angular/forms';
import { UserService } from '../../services/user.service';
import { ApiError } from '../../models/apierror';
import { UniqueUsername } from '../class/unique-username';
#Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.css'],
})
export class RegisterComponent implements OnInit {
error!: ApiError;
submitted = false;
registrationForm!: FormGroup;
constructor(
private fb: FormBuilder,
private router: Router,
private userService: UserService,
private uniqueUsername: UniqueUsername
) {}
ngOnInit(): void {
this.registrationForm = this.fb.group({
name: ['', Validators.required],
username: [
'',
[Validators.required],
[this.uniqueUsername.validate.bind(this.uniqueUsername)],
],
password: ['', Validators.required],
});
}
get name() {
return this.registrationForm.get('name');
}
get username() {
return this.registrationForm.get('username');
}
get password() {
return this.registrationForm.get('password');
}
onSubmit() {
const formData = new FormData();
formData.append('name', this.registrationForm.get('name')!.value);
formData.append('username', this.registrationForm.get('username')!.value);
formData.append('password', this.registrationForm.get('password')!.value);
}
gotoHome() {
this.router.navigate(['/']);
}
}
Async Validator class code::
import { Injectable } from '#angular/core';
import {
AbstractControl,
AsyncValidator,
ValidationErrors,
} from '#angular/forms';
import { Observable, of } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { UserService } from '../../services/user.service';
#Injectable({ providedIn: 'root' })
export class UniqueUsername implements AsyncValidator {
constructor(private userService: UserService) {}
validate(control: AbstractControl): Observable<ValidationErrors | null> {
const { value } = control;
return this.userService.checkUsername(value).pipe(
map((isExist: boolean) => (isExist ? { uniqueUserName: true } : null)),
catchError(() => of(null))
);
}
}
Combine AbstractControlOptions with FormBuilder:
this.registrationForm = new FormGroup(
this.fb.group({
name: ['', Validators.required],
username: [
'',
[Validators.required],
[this.uniqueUsername.validate.bind(this.uniqueUsername)],
],
password: ['', Validators.required],
}).controls, {
updateOn: 'blur'
}
);
Using the constructor of FormGroup and FormControl
form=new FormGroup({
...
username:new FormControl('',{
validators:Validators.required,
asyncValidators:this.uniqueUsername.validate.bind(this.uniqueUsername),
updateOn:'blur'
}
)
})
Using FormBuilder
form=this.fb.group({
...
username:this.fb.control('',{
validators:Validators.required,
asyncValidators:this.uniqueUsername.validate.bind(this.uniqueUsername),
updateOn:'blur',
})
})
//or
form=this.fb.group({
...
username:['',{
validators:Validators.required,
asyncValidators:this.uniqueUsername.validate.bind(this.uniqueUsername),
updateOn:'blur',
}]
})
You can use updateOn:'blur' from AbstractControlOptions interface. Other option available are change & submit

How to fix "Cannot read property '...' of undefined" when calling angular service method inside template

I created a new service in my project and I added some functions to it.
When I tried to call a service function from my component template I got this error "Cannot read property 'isCompanyEligible' of undefined"
I tried to create new function inside my component and assign the service function to it but I got the same error.
This is my service:
import { FinancialHealth } from 'src/app/shared/models/financial-health';
import { LocalStoreService } from 'src/app/shared/services/local-store.service';
import {Application} from './../models/application';
import {Injectable} from '#angular/core';
import { NgbDateParserFormatterService} from './ngb-date-parser-formatter.service ';
#Injectable({
providedIn: 'root'
})
export class EligibilityService {
application: Application;
activityAreas = [];
areasEligibility = [];
legalForms = [];
jobPositions = [];
constructor(
private ls: LocalStoreService,
private dateService: NgbDateParserFormatterService
) {
this.application = this.ls.getItem('application');
const {
activity_areas,
legal_forms,
job_positions,
areas_eligiblity
} =
this.ls.getItem('shared_data').data;
this.activityAreas = activity_areas;
this.legalForms = legal_forms;
this.jobPositions = job_positions.filter(job => job.is_management_position ==
1);
this.areasEligibility = areas_eligiblity;
}
public isCompanyEligible(application ? ) {
if (application) {
this.application = application;
}
if (!this.application || (!this.application.company)) {
return null;
}
const company = this.application.company;
let age;
if (typeof this.application.company.established_at == 'object') {
const date =
this.dateService.format(this.application.company.established_at);
age = this.getAge(date);
} else {
age = this.getAge(company.established_at)
}
return this.legalForms.includes(company.legal_form) && (age >= 2 && age <=
5);
}
growthRate(firstYear, secondYear) {
if (!firstYear || !secondYear) {
return 0;
}
return Math.round(((secondYear - firstYear) / firstYear) * 100);
}
}
This is my component.ts:
import { Component, OnInit } from '#angular/core';
import { CustomValidators } from 'ng2-validation';
import { FormGroup, FormBuilder, FormControl } from '#angular/forms';
import { ToastrService } from 'ngx-toastr';
import { DataLayerService } from 'src/app/shared/services/data-layer.service';
import { BreadcrumbService } from '../../../shared/services/breadcrumb.service';
import { EligibilityService } from 'src/app/shared/services/eligibility.service';
#Component({
selector: 'app-form-sommaire',
templateUrl: './sommaire.component.html',
styleUrls: ['./sommaire.component.scss']
})
export class SommaireFormComponent implements OnInit {
formBasic: FormGroup;
loading: boolean;
radioGroup: FormGroup;
sharedData: any;
isValid: Boolean = false;
application: any;
breadcrumb: { label: string; route: string; }[];
title: String = 'Sommaire';
constructor(
private fb: FormBuilder,
private toastr: ToastrService,
private ls: LocalStoreService,
private appService: ApplicationService,
private data: BreadcrumbService,
public eligibility: EligibilityService
) { }
}
This is my HTML template:
<div class="col-lg-2">
<i *ngIf="eligibility.isCompanyEligible()" class="icon ion-ios-checkmark-circle large-success"></i>
<i *ngIf="eligibility.isCompanyEligible() === false" class="icon ion-ios-close-circle large-danger"></i>
<i *ngIf="eligibility.isCompanyEligible() == null" class="icon ion-md-alert large-warning"></i>
</div>
Anything marked as private cannot be accessed by the component's template either. (Private members can be accessed when using JIT, such as at development time, but not when using AOT, such as for production.)
Actually, best practice is to wrap any service properties/methods in a component property/method and have the template bind to/call the component's property or method to access the service data.
Something like this:
get isCompanyEligible(): boolean {
return this.eligibility.isCompanyEligible();
}
and use it in your template: - <i *ngIf="isCompanyEligible()"
OR
Make the EligibilityService injection public in constructor of component, to access inside template:
constructor(
private fb: FormBuilder,
private toastr: ToastrService,
private ls: LocalStoreService,
private appService: ApplicationService,
private data: BreadcrumbService,
public eligibility: EligibilityService
) { }

Can't resolve all parameters for component: (?, [object Object]) on jasmine component UT

I'm defining a UT of a component that has a extended class and use both i8nService (for translations purpose) and ChangeDetectionRef and unable to instantiate it due to the following error:
Failed: Can't resolve all parameters for BrandingMultiselectComponent: (?, [object Object]).
Error: Can't resolve all parameters for BrandingMultiselectComponent: (?, [object Object]).
at syntaxError node_modules/#angular/compiler/fesm5/compiler.js:2426:1)
at CompileMetadataResolver.push../node_modules/#angular/compiler/fesm5/compiler.js.CompileMetadataResolver._getDependenciesMetadata node_modules/#angular/compiler/fesm5/compiler.js:18979:1)
at CompileMetadataResolver.push../node_modules/#angular/compiler/fesm5/compiler.js.CompileMetadataResolver._getTypeMetadata node_modules/#angular/compiler/fesm5/compiler.js:18872:1)
at CompileMetadataResolver.push../node_modules/#angular/compiler/fesm5/compiler.js.CompileMetadataResolver.getNonNormalizedDirectiveMetadata node_modules/#angular/compiler/fesm5/compiler.js:18491:1)
at CompileMetadataResolver.push../node_modules/#angular/compiler/fesm5/compiler.js.CompileMetadataResolver.loadDirectiveMetadata node_modules/#angular/compiler/fesm5/compiler.js:18353:1)
at http://localhost:9876/_karma_webpack_/webpack:/node_modules/#angular/compiler/fesm5/compiler.js:26011:1
at Array.forEach (<anonymous>)
at http://localhost:9876/_karma_webpack_/webpack:/node_modules/#angular/compiler/fesm5/compiler.js:26010:1
at Array.forEach (<anonymous>)
at JitCompiler.push../node_modules/#angular/compiler/fesm5/compiler.js.JitCompiler._loadModules node_modules/#angular/compiler/fesm5/compiler.js:26007:1),Expected undefined to be defined.
at UserContext.<anonymous> src/app/wa/components/branding/ddl-multiselect/ddl-multiselect.component.spec.ts:62:23)
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke node_modules/zone.js/dist/zone.js:391:1)
at ProxyZoneSpec.push../node_modules/zone.js/dist/zone-testing.js.ProxyZoneSpec.onInvoke node_modules/zone.js/dist/zone-testing.js:289:1)
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke node_modules/zone.js/dist/zone.js:390:1)
This is the UT I've prepared so far:
import { CUSTOM_ELEMENTS_SCHEMA } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { async, ComponentFixture, TestBed } from '#angular/core/testing';
import { RouterTestingModule } from '#angular/router/testing';
import { AngularMultiSelectModule } from 'angular2-multiselect-dropdown';
import { I18nService } from '#core/language/i18n.service';
import { BrandingMultiselectComponent } from '#branding/ddl-multiselect/ddl-multiselect.component';
let component: BrandingMultiselectComponent ;
let fixture: ComponentFixture<BrandingMultiselectComponent >;
let ngOnitComponent_Spy: jasmine.Spy;
let I18nServiceStub: Partial<I18nService>;
describe('branding component - BrandingMultiselectComponent - testing initialization', () => {
I18nServiceStub = {
language: 'en-US',
supportedLanguages: ['en-US', 'es-ES']
};
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ BrandingMultiselectComponent ],
imports: [
BrowserModule,
AngularMultiSelectModule,
RouterTestingModule
],
schemas: [ CUSTOM_ELEMENTS_SCHEMA ],
providers: [ { provide: I18nService, useClass: I18nServiceStub } ]
})
.compileComponents();
fixture = TestBed.createComponent(BrandingMultiselectComponent );
component = fixture.componentInstance;
// Spies for component stuff
ngOnitComponent_Spy = spyOn(component, 'ngOnInit').and.callThrough();
}));
it('should component be defined', () => {
expect(component).toBeDefined();
});
});
And this is the component itself (not everything is set though)
import { Component, Input, Output, EventEmitter,
ViewEncapsulation, OnInit, AfterViewChecked,
ChangeDetectorRef, AfterViewInit, ViewChild } from '#angular/core';
import { ArrayUtil } from '#utils/ArrayUtil/ArrayUtil';
import { ObjectUtil } from '#utils/ObjectUtil/ObjectUtil';
import { I18nService } from '#core/index';
import { BaseTranslation } from '#app/components/base/base.translations';
import { DDLPluginTexts, DDLMultiselectComponent } from '#shared/components/single/ddl-multiselect/ddl-multiselect.component';
#Component({
selector: 'wa-ddl-multiselect',
templateUrl: './ddl-multiselect.component.html',
styleUrls: ['./ddl-multiselect.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class BrandingMultiselectComponent extends BaseTranslation implements OnInit, AfterViewInit, AfterViewChecked {
// Required params
//#region OPTIONS
sOptions: any[];
backupRowOpts: any[];
#Output() optionsChange: EventEmitter<any[]> = new EventEmitter<any[]>();
#Input()
get options() {
return this.sOptions;
}
set options(val: any[]) {
if (!ArrayUtil.AreEqual(this.sOptions, val)) {
if (!this.hasComponentAlreadyBeenInitialized) {
this.backupRowOpts = val;
}
this.sOptions = val;
this.optionsChange.emit(this.sOptions);
}
}
//#endregion
//#region SELECTED OPTIONS
sSelectedOptions: any[];
#Output() selectedOptionsChange: EventEmitter<any[]> = new EventEmitter<any[]>();
#Input()
get selectedOptions() {
return ArrayUtil.IsNotEmptyOrNull(this.sSelectedOptions) ? this.applyOptionsTranslation(false, this.sSelectedOptions)
: this.sSelectedOptions;
}
set selectedOptions(val: any[]) {
if (!ArrayUtil.AreEqual(this.sSelectedOptions, val)) {
this.sSelectedOptions = val;
// We want to overwrite text shown with the one expected
if (this.hasComponentAlreadyBeenInitialized &&
ArrayUtil.IsNotEmptyOrNull(this.sSelectedOptions) &&
this.ddlSettings.singleSelection === false &&
ObjectUtil.IsNotNullOrUndefined(this.translationTexts)) {
this.defineDdlFooter();
}
this.selectedOptionsChange.emit(this.sSelectedOptions);
}
}
//#endregion
hasComponentAlreadyBeenInitialized = false;
hasOptionsAlreadyBeenTranslated = false;
// Optional params
#Input() doesOptionsRequireTranslations = false;
//#region TRANSLATION TEXTS
originalKeyTranslationTexts: DDLPluginTexts = null;
sTranslationTexts: DDLPluginTexts;
#Output() translationTextsChange = new EventEmitter<DDLPluginTexts>();
#Input()
get translationTexts(): DDLPluginTexts {
return this.sTranslationTexts;
}
set translationTexts(val: DDLPluginTexts) {
if (val !== null && val !== undefined) {
if (this.originalKeyTranslationTexts === null) {
this.originalKeyTranslationTexts = val;
}
this.sTranslationTexts = this.applyTranslations();
this.translationTextsChange.emit(this.sTranslationTexts);
}
}
//#endregion
#Input() displayProp: string;
#Input() valueProp: string;
showToggleAll: boolean;
// Plugin optional params
#Input() isEditionMode = false;
#Input() isFilterActive = false;
#Input() selectionLimit: string = null;
// Shared component ref
#ViewChild(DDLMultiselectComponent) ddlBaseMultiSelect: DDLMultiselectComponent;
// Events
#Output() ddlOptionSelectedEvent = new EventEmitter<any>();
//#region COMPONENT LIFE-CYLCE HOOKS
constructor(_i8nService: I18nService, private cdRef: ChangeDetectorRef) { super(_i8nService); }
ngAfterViewInit(): void {
this.cdRef.detectChanges();
if (this.isLocalPreference) {
const currentUserDefaultPrefs = this.ddlBaseMultiSelect.loadDefaultUserPrefs();
if (ObjectUtil.IsNotNullOrUndefined(currentUserDefaultPrefs)) {
this.selectedOptions = currentUserDefaultPrefs;
} else {
this.selectedOptions = this.options;
}
} else {
if (!ArrayUtil.IsNotEmptyOrNull(this.selectedOptions)) {
this.selectedOptions = this.options;
}
}
this.hasComponentAlreadyBeenInitialized = true;
}
//#endregion
//#region COMPONENT FUNCS
applyTranslations(isForLangChange: boolean = false): DDLPluginTexts {
let resultTranslationsTexts: DDLPluginTexts = null;
if (this.originalKeyTranslationTexts !== null &&
this.originalKeyTranslationTexts !== undefined) {
// Apply translations for input PrimeNG labels
resultTranslationsTexts = {
buttonDefaultText: this.i8nService.getInstantTranslation(this.originalKeyTranslationTexts.buttonDefaultText),
dynamicButtonTextSuffix: '{0} ' + this.i8nService.getInstantTranslation(this.originalKeyTranslationTexts.dynamicButtonTextSuffix),
filterPlaceHolder: this.i8nService.getInstantTranslation(this.originalKeyTranslationTexts.filterPlaceHolder),
emptyFilterMessage: this.i8nService.getInstantTranslation(this.originalKeyTranslationTexts.emptyFilterMessage),
checkAll: this.i8nService.getInstantTranslation(this.originalKeyTranslationTexts.checkAll),
uncheckAll: this.i8nService.getInstantTranslation(this.originalKeyTranslationTexts.uncheckAll),
filterSelectAll: this.i8nService.getInstantTranslation(this.originalKeyTranslationTexts.filterSelectAll),
filterUnSelectAll: this.i8nService.getInstantTranslation(this.originalKeyTranslationTexts.filterUnSelectAll)
};
if (isForLangChange) {
this.translationTexts = resultTranslationsTexts;
}
}
// Apply translations for options (if applies)
if (this.doesOptionsRequireTranslations &&
this.doesOptionsRequireTranslations.valueOf() &&
ArrayUtil.IsNotEmptyOrNull(this.backupRowOpts)) {
this.hasOptionsAlreadyBeenTranslated = false;
this.applyOptionsTranslation(true);
}
return resultTranslationsTexts;
}
applyOptionsTranslation(isForLangChange: boolean = false, optionsToTranslate: any[] = null): any[] {
// tslint:disable-next-line:prefer-const
let optionsTranslated = ArrayUtil.Clone(ArrayUtil.IsNotEmptyOrNull(optionsToTranslate) ? optionsToTranslate
: this.backupRowOpts);
optionsTranslated.forEach(option => {
option[this.displayProp] = this.i8nService.getInstantTranslation(option[this.displayProp]);
});
if (isForLangChange) {
this.options = this.backupRowOpts;
}
return optionsTranslated;
}
//#endregion
}
#endregion
}
What am I missing here? Is there something to defined? As far as I understand it should have something to do with the 18nService but I'm 100% sure.
Any suggestions are welcome
use NO_ERRORS_SCHEMA to allow unknown elements and attributes
TestBed.configureTestingModule({
declarations: [ BrandingMultiselectComponent ],
imports: [
BrowserModule,
AngularMultiSelectModule,
RouterTestingModule
],
schemas: [ NO_ERRORS_SCHEMA ], // here
providers: [ { provide: I18nService, useClass: I18nServiceStub } ]
}).compileComponents();

Sharing an object from cone component to another Angular 2

I want to share an object from my first component to the second. I am able to log the 'strVal'(string) defined in the Login Component, in my Home Component but I am unable to log the value of 'abc'(Object) from the Login Component, in the HomeComponent. I am confused why one value from Login Component gets available to Home Component and other does not! The code for Login Component in below
Login.Component.ts
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
import { AuthenticationService } from '../_services/index';
import { User } from '../contract';
#Component({
moduleId: module.id,
templateUrl: 'login.component.html'
})
export class LoginComponent implements OnInit {
model: any = {};
loading = false;
error = '';
us: User[];
abc: any[];
strVal: string = "Rehan";
current: any;
constructor(
private router: Router,
private authenticationService: AuthenticationService) { }
ngOnInit() {
// reset login status
this.authenticationService.logout();
this.getUs();
}
login() {
this.loading = true;
this.authenticationService.login(this.model.username, this.model.password)
.subscribe(result => {
if (result) {
this.router.navigate(['/']);
}
else {
alert('Username and Password Incorrect');
this.loading = false;
this.model = [];
this.router.navigate(['/login']);
}
});
}
getUs() {
this.authenticationService.getUsers().subscribe(
res => this.us = res
);
}
chek() {
this.abc = this.us.filter(a => a.Login === this.model.username);
console.log(this.abc);
}
}
Home.Component.ts
import { Component, OnInit, Input } from '#angular/core';
import { AuthenticationService } from '../_services/index';
import { LoginComponent } from '../login/index';
import { User } from '../contract';
#Component({
moduleId: module.id,
templateUrl: 'home.component.html',
providers: [LoginComponent]})
export class HomeComponent implements OnInit {
users: User[];
constructor(private userService: AuthenticationService, private Log: LoginComponent) { }
ngOnInit() {
this.userService.getUsers().subscribe(
res => this.users = res
);
console.log(this.Log.strVal);
console.log(this.Log.abc);
}
}
Any hint or help will be appreciated. Thanks!

Categories

Resources