Je suis peu confus sur la façon dont je devrais travailler avec Angular 2 quand j'ai besoin <input>
tags à l'intérieur des balises <tr>
d'une table, lorsque les balises <tr>
sont générés par un *ngFor
. Ma situation est la suivante: j'ai un tableau de "produits", je devrais montrer l'information du produit sur les étiquettes <tr>
et, pour chaque produit, un champ input
pour augmenter le stock de chaque produit. Voilà ce que je l'ai fait:Angular forme d'entrée dans * ngFor
ProductStokeComponent.ts
export class ProductStokeComponent implements OnInit {
form: FormGroup;
products: Subject<Product[]> = new Subject();
constructor(
private productService: ProductService,
private formBuilder: FormBuilder,
) { }
ngOnInit() {
this.formInit();
this.getProducts();
}
formInit() {
this.form = this.formBuilder.group({
products: this.formBuilder.array([])
});
}
getProducts() {
this.productService.getProducts().subscribe(data => {
this.products.next(data);
});
}
}
ProductStokeComponent.html
<form [formGroup]="form" (ngSubmit)="formSubmit()">
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Stock</th>
<th>Stock Entrance</th>
</tr>
</thead>
<tbody formArrayName="products">
<tr *ngFor="let product of products| async">
<td>{{ product.id }}</td>
<td>{{ product.name }}</td>
<td>{{ product.stock }}</td>
<td>
<input type="number" name="stock[product.id]" >
</td>
</tr>
</tbody>
</table>
<button type="submit">Add Stock</button>
</form>
En html pur, j'ai pu en finir avec un tableau nommé, mais avec angulaire 2 J'essaie d'utiliser une forme réactive, mais ensuite je devrais utiliser une boucle for pour remplir le formulaire après une boucle pour générer la table pour chaque produit, cela ressemble à l'utilisation de beaucoup de ressources pour faire une chose simple.
Mise à jour avec des méthodes de forme réactive
ProductStokeComponent.ts
ngOnInit() {
this.formInit();
this.getProducts();
}
formInit(product?: Product) {
this.form = this.formBuilder.group({
products: this.formBuilder.array([])
});
}
ProductStokeComponent.html
<tbody formArrayName="products">
L'idée est de mettre en 'input 'le nombre d'éléments à ajouter au stock? – MondKin
oui, devrait être un nombre d'entrée –