Angular 6属性指令字段未定义

时间:2019-02-06 20:09:49

标签: angular

我使用Angular6。我有一个包含4个字段的表单。其中两个是价格和数量。我想在另一个字段中显示价格和数量的乘积。

我定义了一个属性指令。我想在div中显示指令paModel totalPrice的字段。我在表单字段中定义了一个事件。

这是我的表格

<form novalidate [formGroup]="form" (ngSubmit)="submitForm(form)">
  <div class="form-group" *ngFor="let control of form.productControls">
    <label>{{ control.label }}</label>
    <input
      class="form-control"
      [(ngModel)]="newProduct[control.modelProperty]"
      name="{{ control.modelProperty }}"
      formControlName="{{ control.modelProperty }}"
      [paModel]="newProduct[control.modelProperty]"
      (paModelChange)="newProduct[control.modelProperty] = $event"
      [pa-product]="newProduct"
      #paModel="paModel"
    />
    <ul class="text-danger list-unstyled" *ngIf="(formSubmitted || control.dirty) && !control.valid">
      <li *ngFor="let error of control.getValidationMessages()">{{ error }}</li>
    </ul>
  </div>
  <div class="bg-primary text-white">{{ paModel.totalPrice }}</div>
  <button
    class="btn btn-primary"
    type="submit"
    [disabled]="formSubmitted && !form.valid"
    [class.btn-secondary]="formSubmitted && !form.valid"
  >
    Create
  </button>
</form>

属性指令名称为paModel。这是我的paModel指令

import { Input, Output, EventEmitter, Directive, HostBinding, HostListener, SimpleChange } from "@angular/core";
import {Product } from "./product.model"

@Directive({
    selector: "input[paModel]",
    exportAs: "paModel"
})
export class PaModel {

    direction: string = "None";

    @Output("pa-totalprice")
    totalPrice: number = 0;

    @Input("paModel")
    modelProperty: string;

    @Input("pa-product")
    product: Product;

    @HostBinding("value")
    fieldValue: string = "";

    ngOnChanges(changes: { [property: string]: SimpleChange }) {
        console.log("en ngOnChanges");
        let change = changes["modelProperty"];
        if (change.currentValue != this.fieldValue) {
            this.fieldValue = changes["modelProperty"].currentValue || "";
            this.direction = "Model";
            this.totalPrice = 0;
        }
    }

    @Output("paModelChange")
    update = new EventEmitter<string>();

    @HostListener("input", ["$event.target.value"])
    updateValue(newValue: string) {
        console.log("en updateValue");
        console.log("name ",this.product.name)
        console.log("price ",this.product.price)
        console.log("quantity ",this.product.quantity)
        if (this.product.price != undefined && this.product.quantity != undefined) {
            this.totalPrice = this.product.price * this.product.quantity;
        } else {
            this.totalPrice = 0;
        }
        this.fieldValue = newValue;
        this.update.emit(newValue);
        this.direction = "Element";
    }
}

在控制台中,我看到错误

ERROR TypeError: Cannot read property 'totalPrice' of undefined
    at Object.eval [as updateRenderer] (ProductFormComponent.html:18)
    at Object.debugUpdateRenderer [as updateRenderer] (core.js:10879)
    at checkAndUpdateView (core.js:10255)
    at callViewAction (core.js:10491)
    at execComponentViewsAction (core.js:10433)
    at checkAndUpdateView (core.js:10256)
    at callViewAction (core.js:10491)
    at execComponentViewsAction (core.js:10433)
    at checkAndUpdateView (core.js:10256)
    at callWithDebugContext (core.js:11143)

如何在div中显示字段totalPrice?

已编辑

我修改了我的代码。现在我有了html

<div class="form-group bg-info text-white p-2">
  <input class="bg-primary text-white" [(paModel)]="newProduct" #paModel="paModel" />
  <div *ngIf="paModel" class="bg-primary text-white">Total Price : {{ paModel.totalPriceString }}</div>
</div>

我有两种方法

ngOnChanges(changes: { [property: string]: SimpleChange }) {

    let change = changes["modelProperty"];
    /* if (change.currentValue != this.fieldValue) { */

        this.fieldValue = changes["modelProperty"].currentValue || "";

        this.direction = "Model";
        if (this.product.price != undefined && this.product.quantity != undefined) {
        this.totalPrice = this.product.price * this.product.quantity;
    } else {

        this.totalPrice = 0;
    }

    this.totalPriceString = this.totalPrice.toString();

   /*  } */
}

@Output("paModelChange")
update = new EventEmitter<string>();

@HostListener("input", ["$event.target.value"])
updateValue(newValue: string) {

    if (this.product.price != undefined && this.product.quantity != undefined) {
        this.totalPrice = this.product.price * this.product.quantity;
    } else {
        this.totalPrice = 0;
    }
    this.fieldValue = newValue;


    this.update.emit(newValue);
    this.direction = "Element";
    this.totalPriceString = this.totalPrice.toString();
} 

在这些方法的最后,totalPrice具有乘法功能,但值不会显示在div中。

我该如何解决?

1 个答案:

答案 0 :(得分:0)

查看您的输入,您应该尝试访问modelProperty,而不是paModel

@Input("paModel") modelProperty: string; // in the current component it is modelProperty

然后我想您正在尝试在传递数据之前访问子级,因此它是undefined,直到传递值为止。因此您的html应该看起来像这样

<div class="bg-primary text-white">{{modelProperty?.totalPrice}}</div>

或类似的

<div *ngIf="paModel" class="bg-primary text-white">{{paModel.totalPrice}}</div>

?运算符仅在定义父对象时显示子值。或者,您可以使用*ngIf从dom中删除html,直到定义了该值为止。