我正在创建一个html表。其中有一个按钮的单元格和一个通过 ngFor 创建的下拉菜单。如果没有从下拉菜单中选择任何值,如何禁用按钮(通过 ngFor 生成)。我已经尝试过了:
在 AppComponent 中,我的表情是这样的:
ts
customers: Array<Object> = [];
level: string;
changedvalue(event: Event) {
const value = (<HTMLSelectElement>event.target).value;
this.level = value;
}
html
<tbody>
<tr *ngFor="let customer of customers">
<td> {{ customer.uid }} </td>
<td> {{ customer.name }} </td>
<td> {{ customer.level }}</td>
<td>
<select (change)="changedvalue($event)" class="form-control" name="level">
<option hidden selected> -- select an option -- </option>
<option>Level 1</option>
<option>Level 2</option>
</select>
</td>
<td><button [disabled]=!level >Send</button></td>
</tr>
</tbody>
此代码的问题是,如果从任何下拉列表中选择值,它将使所有按钮包含在内。我想要的是仅启用该下拉菜单前面的那个按钮。如何将每个按钮与我通过 ngFor 创建的每个下拉列表相关联。
答案 0 :(得分:0)
然后,您应该在customer
中存储一些值,以便每次迭代都具有自己的level
变量。我根据约定更改了方法名称。
<tbody>
<tr *ngFor="let customer of customers">
<td> {{ customer.uid }} </td>
<td> {{ customer.name }} </td>
<td> {{ customer.level }}</td>
<td>
<select (change)="onLevelChange($event, customer)" class="form-control" name="level">
<option hidden selected> -- select an option -- </option>
<option>Level 1</option>
<option>Level 2</option>
</select>
</td>
<td><button [disabled]=!customer.level >Send</button></td>
</tr>
</tbody>
customers: Array<Object> = [];
onLevelChange(event: Event, customer) {
const value = (<HTMLSelectElement>event.target).value;
customer.level = value;
// if compiler complains as "there is no level property of customer"
// you can do following
// customer['level'] = value;
}
答案 1 :(得分:0)
尝试这样的事情:
手动为客户模型添加级别,然后执行以下操作
<tbody>
<tr *ngFor="let customer of customers">
<td> {{ customer.uid }} </td>
<td> {{ customer.name }} </td>
<td> {{ customer.level }}</td>
<td>
<select (change)="customer.level = !customer.level" class="form-control" name="level">
<option hidden selected> -- select an option -- </option>
<option>Level 1</option>
<option>Level 2</option>
</select>
</td>
<td><button [disabled]=!customer.level >Send</button></td>
</tr>
</tbody>
答案 2 :(得分:0)
您可以将自定义属性添加到customers
对象中。
有效的堆叠闪电战:https://stackblitz.com/edit/angular-2m8ns7?file=src%2Fapp%2Fapp.component.ts
示例代码:
<div *ngFor="let c of customers; let i = index">
<span>{{c.name}} {{c.surname}} | is Enabled? : {{c.isEnabled}}</span>
<button (click)="toggleMe(i)">Toggle status</button>
</div>
从'@ angular / core'导入{组件};
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
public customers : any[] = [];
constructor(){
this.customers = [
{
name: "Jhon",
surname: "Cena",
isEnabled: false
},
{
name: "Mike",
surname: "Mya",
isEnabled: false
},
{
name: "Sandy",
surname: "Rivers",
isEnabled: false
}
];
}
toggleMe(i){
this.customers[i].isEnabled = !this.customers[i].isEnabled;
}
}