我无法将ID属性分配给某些HTML按钮。使用Angular 2动态分配HTML按钮ID
categories.service.ts:
getCategories(): Observable<Category[]> {
let headers = new Headers({ 'Authorization': this.authenticationService.token });
let options = new RequestOptions({ headers: headers });
return this.http.get(this.categoriesURL, options)
.map((response: Response) => response.json());
}
categories.component.ts:
import { Component, OnInit } from '@angular/core';
import { Category } from '../../_models/category';
import { CategoriesService } from '../../_services/categories.service';
@Component({
selector: 'app-categories',
templateUrl: './categories.component.html',
styleUrls: ['./categories.component.css']
})
export class CategoriesList implements OnInit {
categories: Category[] = [];
constructor(private categoriesService: CategoriesService) { }
ngOnInit() {
// Limpia el mode
this.categoriesService.clearMode();
// Lista de categorías
this.categoriesService.getCategories()
.subscribe(categories => {
this.categories = categories;
});
}
setMode(event){
this.categoriesService.setMode(event.target["name"], event.target["id"]);
}
}
categories.component.html:
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="content">
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th>Nombre</th>
<th>Descripción</th>
<th></th>
</tr>
</thead>
<tbody>
<tr *ngFor="let category of categories">
<td>{{category.name}}</td>
<td>{{category.description}}</td>
<td><button (click)="setMode($event)" routerLink="/categories/form" type="button" name="editando" id="{{category.id}}" class="btn btn-info"><i class="ti-pencil-alt"></i> Editar</button></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
说明:当“/ categories”加载时,触发getCategories()函数从服务器检索数据。然后它在视图中填充我的表格,并用编辑按钮构建每行,并在末尾带有类别ID作为按钮ID。我正在做的是当用户点击编辑按钮时,触发categories.component.ts中的setMode()函数并检索按钮ID并将模式和ID保存在服务中。查看编辑表单时将使用此模式(因为我使用它来创建和编辑同一资源)ID将用于向服务器请求资源。
错误:有时,当我点击编辑按钮时,它会导航到表单,但不会调用服务器来检索资源(我在Chrome中检查了网络选项卡)。我console.log在setMode()函数中的ID,并注意到有时它是不确定的,所以我不认为我的问题是在形式。它随机发生,有时我点击编辑按钮5次,它的作品,下一个给我不确定,有时或多或少。所以我认为这可能与我的要求有关,但我不确定。
我已经尝试过:
- 更改可观察到无极
- 直到 从服务器检索的数据不渲染列表(使用可观察和承诺)
不是真的有关系,但是有没有理由不要'setMode(category.id)'?另外,如果导航看起来太早了,为什么不通过setMode方法末尾的代码进行导航? – Ploppy
@Ploppy在setMode中,我传递了事件对象,在那里我正在检索“名称”和“标识”属性,但你只是给了我一个主意。我将尝试您通过代码进行导航的建议。 – salsadeanguila
@Ploppy我将setMode中的参数更改为'setMode(mode,category_id)'而不是'$ event',现在它按预期工作。也改变了导航,如你所建议,它的工作。我不记得我为什么选择使用'$ event'。你能写一个答案,所以我可以把它标记为正确的吗? – salsadeanguila