我的应用程序在使用 JIT 编译器时似乎可以工作,但是当我尝试使用 ng build --prod
来使用 AOT 编译器时然后它抛出一个错误:
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 团队成员交谈过,这是由于我的选择器未指定元素造成的。因此,当使用 ng build --prod
构建时,Angular 使用 div
作为“最小公分母”:
the error you see refers to because divs are the lowest common denominator of HTML element. If a component selector doesn't specify any other element type, then it becomes a div.
所以有两种解决方案:
1) 使选择器更加具体,以便它仅尝试使用具有 disabled
属性的元素进行 AOT 编译。
将选择器:'[formButton]'
更新为选择器:'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>
关于Angular 6 生产版本 "Can' t 绑定(bind)到 'disabled',因为它不是 'div' 的已知属性”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50382710/