组件的初始值未定义

时间:2019-03-09 13:09:29

标签: angular initialization custom-type

selectedProdGrp.ProductGroupNames为null,因为尚未提取任何数据。我将接口MultiLangTxtModel定义为自定义类型,但是我不确定这是否是正确的方法。

我在控制台中收到以下错误:

NamesComponent.html:9 ERROR TypeError: Cannot read property 'l10n' of undefined

我在做什么错了?

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>&nbsp;<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>

1 个答案:

答案 0 :(得分:1)

您正在尝试从构造函数内部的输入获取数据。同样,破坏性分配似乎是错误的。构造函数不是Angular生命周期挂钩的一部分,此刻(在constructor内部)的输入值为undefined,请尝试将其获取到ngOnInit生命周期挂钩中:

ngOnInit() {
  { l10n: { de: null, en: null,fr: null, it: null } } = this.value;
  console.log(l10n);
}
  

NamesComponent.html:9错误TypeError:无法读取未定义的属性“ l10n”

请确保在HTML模板(value)中可以使用*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">
  ...