首页 > 解决方案 > Angular 6 生产版本“无法绑定到‘禁用’,因为它不是‘div’的已知属性”

问题描述

我的应用程序在使用 JIT 编译器时似乎可以工作,但是当我尝试使用 AOT 编译器时,ng build --prod它会引发错误:

ERROR in : Can't bind to 'disabled' since it isn't a known property of 'div'. ("[ERROR ->]<div formButton></div>")

我如何弄清楚这个错误来自哪里?

我只是添加了延迟加载的功能模块,而不是导入其中的所有内容,app.module.ts我不知道是否需要导入FormButtonComponent功能模块?

我搜索了代码库,formButton除了button.

这是button.component.ts

import { Component, HostBinding, Input, OnChanges, SimpleChanges } from "@angular/core";

/**
 * Button with loading and disabled states
 */
@Component({
    moduleId: module.id,
    selector: '[formButton]',
    templateUrl: 'button.component.html'
})
export class FormButtonComponent implements OnChanges {
    @Input() loading? = false;
    @Input() disabled? = false;
    @HostBinding('disabled') disabledAttribute = false;

    ngOnChanges(changes: SimpleChanges): void {
        this.updateState();
    }

    updateState(): void {
        this.disabledAttribute = this.disabled || this.loading;
    }
}

button.component.html

<ng-content></ng-content>
<spinner [size]="small" *ngIf="loading"></spinner>

以下是我应用程序中其他地方的一些示例调用:

<button formButton [loading]="template.loading" [disabled]="disabled" class="button" type="submit">Design</button>

<button formButton class="button" [loading]="form.disabled" (click)="save()">Change Password</button>

<button formButton [ngClass]="buttonClass" (click)="upload()" [loading]="uploaderWrapper.isUploading">{{ buttonText }}</button>

标签: angular

解决方案


编辑:我与一位 Angular 团队成员交谈,这是由于我的选择器没有指定元素。因此,当使用ng build --prodAngular构建div作为“最小公分母”时:

您看到的错误指的是因为 div 是 HTML 元素的最低公分母。如果一个组件选择器没有指定任何其他元素类型,那么它就变成了一个 div。

所以有两种解决方案:

1) 使选择器更具体,以便它只尝试使用具有该disabled属性的元素进行 AOT 编译。

更新selector: '[formButton]'selector: 'button[formButton]'

@Component({
    moduleId: module.id,
    selector: 'button[formButton]',
    templateUrl: 'button.component.html'
})

2) 更新为使用attr.disabled而不是disabled. 这样做的缺点是你必须使用value | null而不是true | false因为浏览器寻找disabled属性的存在而不是它的值。

@HostBinding('disabled') disabledAttribute = false;

@HostBinding('attr.disabled') disabledAttribute = false;

使用此模板:

<ng-content></ng-content>
<spinner [size]="small" *ngIf="loading"></spinner>

推荐阅读