我有一个使用ngFor的10个按钮的列表。我想更改按钮的名称以启用和禁用。起初我有Disable
,当我单击按钮时,带有id
的特定按钮应将文本更改为Enable
,但每10个按钮都会更改。
html
<div *ngFor="let task of tasks">
<button (click)="enableDisableRule(task.id)">{{toggleButton}}</button>
</div>
component
toggle = true;
toggleButton = 'Disable';
tasks = [
{"id": 1, "name":"john"},
{"id": 2, "name":"tom"},
.............
.......
{"id":10, "name":"harry"}
]
enableDisableRule(id) {
this.toggle = !this.toggle;
this.toggleButton = this.toggle ? 'Disable' : 'Enable';
}
有人可以让我知道我该怎么做,以便仅更改特定的按钮文本。
感谢您的帮助。谢谢
答案 0 :(得分:1)
您需要为每个Button对象添加两个以上的属性,而不能使用相同的变量。
tasks = [
{"id": 1, "name":"john","toggle":false,"status":'Disable'},
{"id": 2, "name":"tom","toggle":false,"status":'Disable'},
{"id":10, "name":"harry","toggle":false,"status":'Disable'}
];
然后
enableDisableRule(button) {
button.toggle = !button.toggle;
button.status = button.toggle ? 'Disable' : 'Enable';
}
答案 1 :(得分:1)
HTML:
<ng-container *ngFor="let task of tasks">
<button id="btn-{{task.id}}" (click)="toggleMe(task.id)">{{ text }}</button>
</ng-container>
TS:
text = 'Enable';
tasks = [
{"id": 1, "name":"john"},
{"id": 2, "name":"tom"},
{"id":10, "name":"harry"}
]
private toggleMe(id: number): void {
document.getElementById("btn-"+id).innerHTML = document.getElementById("btn-
"+id).innerHTML == "Disable" ? "Enable" : "Disable";
}
答案 2 :(得分:0)
您可以设置活动元素的ID并将其用作文本更改的基础
<div *ngFor="let task of tasks">
<button (click)="enableDisableRule(task.id)">{{getButtonText(task.id)}}</button>
</div>
component
toggle = true;
activeButtonId = null;
tasks = [
{"id": 1, "name":"john"},
{"id": 2, "name":"tom"},
.............
.......
{"id":10, "name":"harry"}
]
enableDisableRule(id) {
this.toggle = !this.toggle;
this.activeButtonId = id;
}
getButtonText(id) {
let buttonText;
id === this.activebuttonId ? buttonText= "Enable" : buttonText = "Disable";
return buttonText;
}
答案 3 :(得分:0)
我将使用selectedButton
存储选定按钮的状态,这样按钮的状态不会保存在模型(任务)
组件
selectedButton = {}
tasks = [
{ "id": 1, "name": "john" },
{ "id": 2, "name": "tom" },
{ "id": 10, "name": "harry" }
];
enableDisableRule(id) {
this.selectedButton[id]= !this.selectedButton[id];
}
模板
<div *ngFor="let task of tasks">
<button (click)="enableDisableRule(task.id)">
{{selectedButton[task.id] ? 'Enabled' : 'Disabled'}}
</button>
</div>
答案 4 :(得分:0)
创建一个函数以向任务对象动态添加其他属性
.middle{
max-height: 100%;
overflow:scroll;
}
并调用此方法为任务对象中的每个任务添加两个属性,然后将enableDisableRule(id)更改为此
addProperties(){
for(task in this.tasks){
task[toogle]=true;
task[toogleButton]="Disable";
}
}