来自@Input 时,将 ngModel 分配给 属性 是未定义的

Assigning ngModel to property is undefined when coming from @Input

我有一个具有以下输入的组件 属性。

@Input() addressAssociation: AccountAssociation;

其中有: address: Address;

Inside Address 有一个 属性 我想绑定到,它是 stateCode.

在我的模板中我有这个:

<div class="fcol-md-4 fcol-xs-12 form-group" *ngIf="!zipCodeValidating && addressAssociation.address">
  <label for="{{name}}State" class="uk-label">State / U.S Territory</label>
  <select [(ngModel)]="addressAssociation.address.stateCode" 
    [disabled]="isListedZipCode"
    #addState="ngModel"
    required>
    <option [ngValue]="state.abbreviation" *ngFor="let state of states">{{state.fullName}} ({{state.abbreviation}})</option>
  </select>
</div>

<div class="text--error" *ngIf="addState.errors && addState.touched">
    <span *ngIf="addState.errors.required">State is required.</span>
</div>

问题是当模板加载时,它总是抛出一个错误说:Cannot read property errors of undefined

此外,我尝试使用 {{addState | json}} 打印变量,但抛出了循环引用错误。而且,只是尝试打印 addState,即使从禁用状态退出并更改其值,它也从未改变。

问题是变量 #addState 显然没有填充 ngModel 关于如何解决这个问题的任何想法?

我认为您的错误来自这段代码

<div class="text--error" *ngIf="addState.errors && addState.touched">
    <span *ngIf="addState.errors.required">State is required.</span>
</div>

尝试将 addState 添加到您的 ngIf

*ngIf="addState && addState.errors && addState.touched"

addState 未在组件加载时定义,因此 addState.errors 产生该错误

更新的答案:

您遇到了范围界定问题。您在 *ngIf 中分配 #addState。然后你在 *ngIf 之外引用 addState。这是行不通的——模板变量只能在创建它的同一范围内使用。尝试将错误测试 div 移到 *ngIf 中。把它放在 </select>

的正下方

旧答案:

您应该使用安全导航运算符(https://angular.io/guide/template-syntax#safe-navigation-operator)

<div class="text--error" *ngIf="addState?.errors && addState?.touched">
    <span *ngIf="addState?.errors.required">State is required.</span>
</div>