【发布时间】:2018-10-24 10:52:44
【问题描述】:
tl;dr - 我如何让 myButton 组件上的 click() 处理程序来支持按钮的禁用状态?
我有一个自定义按钮组件,用于组件化具有相似外观和感觉的按钮,包括文本和 FA 图标。按钮组件获得某些输入,包括其文本和是否禁用的标志。禁用时,它会正确显示(即变暗和禁止吸烟光标),但其 click() 处理程序始终会收到点击。
我想我知道为什么会发生这种情况,但我不知道如何解决它。我尝试在按钮组件上声明 Output() click = new EventEmitter<any>(),认为 Angular 会以某种方式正确连接它,但那不起作用。
我的按钮的使用者会这样做:
//foo.component.html
...
<my-button
(click)="saveWidget()"
[disabled]="shouldBeDisabled"
type="{{buttonTypes.save}}">
</myButton>
...
//foo.component.ts
import { ButtonTypes } from './myButton';
export class FooComponent implements OnInit {
buttonTypes = ButtonTypes;
saveWidget() {
//do some saving
}
get shouldBeDisabled() {
return true; //Normally a real test in here
}
...
}
我的问题是,当使用此按钮时,无论my-button 的禁用状态如何,都会调用单击处理程序(即 foo.component 上的 saveWidget())。
按钮组件看起来像这样:
export enum ButtonTypes {
add,
cancel,
save,
}
@Component({
selector: 'my-button',
template: `<button [type]="tagType"
[disabled]="disabled"
[ngClass]="btnClasses">
<i *ngIf="hasLeft" class="fa" [ngClass]="iconCls" aria-hidden="true"></i>
<span class="hidden-xs hidden-sm">{{text}}</span>
<i *ngIf="hasRight" class="fa" [ngClass]="iconCls" aria-hidden="true"></i>
</button>`
})
export class ButtonComponent implements OnInit {
@Input() disabled = false;
@Input('type') btnType: ButtonTypes;
@Input() color?: ButtonColor;
@Input() size?: ButtonSize;
...
}
【问题讨论】:
-
自定义属性
disabled的@Input()在ButtonComponent中看起来像什么? -
您是否也知道 add/save/cancel 不是标准 HTML
<button>元素的类型? HTML <button> type Attribute。有效类型为“button”、“submit”和“reset”。 -
更新为包含按钮
@Inputs -
这些答案对您有帮助吗?
标签: angular typescript