Angular 在属性指令中使用DoCheck
我创建了一个简单的应用程序,使用Angular 在属性指令中使用DoCheck,angular,angular2-directives,Angular,Angular2 Directives,我创建了一个简单的应用程序,使用ngFor从数组创建一系列按钮。单击按钮时,其值将被推送到第二个数组 我有一个属性指令disable,它使用DoCheck()侦听对数组的更改,并禁用数组中已经存在其值的任何按钮,以防止它被多次添加 这一切都可行,但有更好的方法吗?Angular 2网站建议使用DoCheck()时要小心 查看 <ul> <li *ngFor="let myitem of myitems">{{ myitem }} <a href="#"
ngFor
从数组创建一系列按钮。单击按钮时,其值将被推送到第二个数组
我有一个属性指令disable
,它使用DoCheck()
侦听对数组的更改,并禁用数组中已经存在其值的任何按钮,以防止它被多次添加
这一切都可行,但有更好的方法吗?Angular 2网站建议使用DoCheck()
时要小心
查看
<ul>
<li *ngFor="let myitem of myitems">{{ myitem }}
<a href="#" (click)="deleteItem(myitem)"> x</a>
</li>
</ul>
<button *ngFor="let item of items" (click)="addItem(item)" [disable]="myitems">{{item}}</button>
您可以绑定到
按钮的[disabled]
属性。在控制器isButtonDisabled(button)
中创建一个函数,从模板中传递项目
<button
*ngFor="let item of items"
(click)="addItem(item)"
[disable]="myitems"
[disabled]="isButtonDisabled(item)"
>
{{item}}
</button>
{{item}}
在函数内部,检查该项是否已推入第二个数组
如果是,则返回true
以禁用按钮。为什么不在组件中执行签入addItem()
方法,而不是使用指令
DoCheck()
方法应具有有限的用途,因为它将在每次更改检测周期运行时运行。所以你在使用它时必须小心
最好使用OnChanges()
而不是DoCheck()
,因为前者仅在输入
属性发生更改时运行
您可以尝试:
export class MyComponent implents OnChanges{
addItem(item) {
if(this.myitems.find(item => item === this.el.nativeElement.innerText)) {
this.renderer.setElementProperty(this.el.nativeElement, 'disabled', true);
this.renderer.setElementClass(this.el.nativeElement, 'disabled', true);
}
else {
this.renderer.setElementProperty(this.el.nativeElement, 'disabled', false);
this.renderer.setElementClass(this.el.nativeElement, 'disabled', false);
}
}
}
ngOnChanges() {
this.addItem(item);
}
在您的情况下,可以跳过使用指令
如果确实要使用指令
,则将所有逻辑从DoCheck()
转移到OnChanges()
export class MyComponent implents OnChanges{
addItem(item) {
if(this.myitems.find(item => item === this.el.nativeElement.innerText)) {
this.renderer.setElementProperty(this.el.nativeElement, 'disabled', true);
this.renderer.setElementClass(this.el.nativeElement, 'disabled', true);
}
else {
this.renderer.setElementProperty(this.el.nativeElement, 'disabled', false);
this.renderer.setElementClass(this.el.nativeElement, 'disabled', false);
}
}
}
ngOnChanges() {
this.addItem(item);
}