selectedProdGrp.ProductGroupNames is null because no data has been fetched yet. I defined the interface MultiLangTxtModel as a custom type but i am not sure if this was the proper approach.
i get the following error in the console:
NamesComponent.html:9 ERROR TypeError: Cannot read property 'l10n' of undefined
what am i doing wrong?
names.components.ts
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'field-names',
templateUrl: './names.component.html',
styleUrls: ['./names.component.scss']
})
export class NamesComponent {
@Input('disabled') editMode;
@Input() value: MultiLangTxtModel;
@Output() value2 = new EventEmitter<MultiLangTxtModel>();
constructor() {
this.value = {l10n:{de:null,en:null,fr:null,it:null}} //didnt help
}
onChange() {
this.value2.emit(this.value);
}
}
names.component.html
<div class="item noBottom" [ngClass]="{
'has-danger': nameEn.invalid || nameFr.invalid || nameDe.invalid || nameIt.invalid,
'has-success': nameEn.valid && nameFr.valid && nameDe.valid && nameIt.valid
}">
<div class="d-flex" [ngStyle]="{'display': (lang != 'en' && lang !='*') ? 'none !important' : 'inherit'}">
<div class="col-md-2 label" i18n="@@tables.general.name">Name {{lang}}</div>
<div class="col-md-1 flag en"></div>
<div class="col-md-9">
<input type="text" class="form-control" accesskey="e" id="nameEn" placeholder="Name" required alphaNumValidator [(ngModel)]="value.l10n.en" (click)="onChange()" name="nameEn" #nameEn="ngModel" [disabled]="!editMode">
<div *ngIf="nameEn.errors && (nameEn.dirty || nameEn.touched)" class="form-control-feedback" >
<p *ngIf="nameEn.errors.alphaNum" class="alert alert-danger"><span i18n="@@tables.general.name">c</span> <span i18n="@@tables.error.alphaNum">a</span></p>
</div>
</div>
</div>
</div>
app.d.ts
interface MultiLangTxtModel {
l10n: {
de:string,
en:string,
fr:string,
it:string
}
}
AppComponent.component.html
<div class="row panel header">
<div class="col-md-4 itemBox">
<field-names [value]="selectedProdGrp.ProductGroupNames" (value2)="onNamesChange($event)"></field-names>
</div>
</div>
You're trying to get data from input inside of the constructor. Also destructuring assignment seems to be wrong. Constructor is not a part of Angular lifecycle hooks, at this moment (inside of constructor
) input value is undefined
, try to get it inside of ngOnInit
lifecycle hook:
ngOnInit() {
{ l10n: { de: null, en: null,fr: null, it: null } } = this.value;
console.log(l10n);
}
NamesComponent.html:9 ERROR TypeError: Cannot read property 'l10n' of undefined
Make sure that you're using properties of value
after it gets available in html template (*ngIf="value"
):
<div class="col-md-9" *ngIf="value">
<input type="text" class="form-control" accesskey="e" id="nameEn" placeholder="Name" required alphaNumValidator [(ngModel)]="value.l10n.en" (click)="onChange()" name="nameEn" #nameEn="ngModel" [disabled]="!editMode">
...