在Angular 2中,如何使用NgFor在重复列表中与NgModel进行双向绑定.下面是我的plunkr和代码,但我收到一个错误.
@Component({
selector: 'my-app',
template: `
<div>
<div *ngFor="let item of toDos;let index = index;">
<input [(ngModel)]="item" placeholder="item">
</div>
Below Should be binded to above input box
<div *ngFor="let item of toDos">
<label>{{item}}</label>
</div>
</div>
`,
directives: [MdButton, MdInput]
})
export class AppComponent {
toDos: string[] =["Todo1","Todo2","Todo3"];
constructor() {}
ngOnInit() {
}
}
Run Code Online (Sandbox Code Playgroud) 我正在构建一个开发票应用程序来学习Angular2.我遇到的问题是如何构建行项目组件,其中一行包含3个应该来自的输入并绑定到行项目数组中的对象.
在角度1中,我可以通过向ng-form输入的容器添加指令来轻松实现此目的.这里的等价物是什么?
这是我的代码:
HTML:
<form name="form" ng-submit="$ctrl.submit(form)" novalidate>
<!-- some more code -->
<ul class="list invoice-table__body">
<li *ngFor="let item of model.lineItems; let i = index">
<input
type="text"
name="description"
class="col-sm-8"
[(ngModel)]="item.description">
<input
type="number"
name="quantity"
class="col-sm-2"
[(ngModel)]="item.quantity">
<input
type="number"
name="total"
class="col-sm-2"
[(ngModel)]="item.total">
</li>
</ul>
<!-- some more code -->
</form>
Run Code Online (Sandbox Code Playgroud)
零件:
import { Component } from '@angular/core';
import { Invoice } from './invoice.model';
import { InvoiceLineItems } from './invoice-line-item.model';
@Component({
selector: 'create-invoice',
templateUrl: 'create-invoice/create-invoice.html'
})
export class CreateInvoiceComponent {
model: …Run Code Online (Sandbox Code Playgroud) 我有一组来自 webservice: 的类别categories,以及一个包含选定类别的数组:selectedCategories
要显示所有复选框,我执行以下操作:
<form [formGroup]="formGroup" (ngSubmit)="onSubmit()">
<div class="row">
<div *ngFor="let category of categories">
<input type="checkbox" class="custom-control-input" [id]="category.id" formControlName="category"
[checked]="categoriesSelected?.includes(category.id)">
<label class="custom-control-label" [for]="category.id">{{ category.name | translate }}</label>
</div>
</div>
</form>
Run Code Online (Sandbox Code Playgroud)
这很好用。
然后我建立我的formGroup:
ngOnInit() {
this.categoriesSelected = this.championships.map(championship => championship.category.id);
this.formGroup = this.formBuilder.group({
categories: this.formBuilder.array([{}])
});
}
Run Code Online (Sandbox Code Playgroud)
现在,我需要的输出只是所选类别的 id。
我对链接 formBuilder 和 formGroup 有点迷茫。
如果我formControlName="categories"在我的模板中添加input标签,所有数据都会消失。
我该怎么做?