嗨,我有一个简单的角度分量的问题,我使用反应形式插入文本,然后按ng循环显示结果
模板
<form [formGroup]="colorsForm">
<div>
<label for="colorName">Color Name</label>
<input id="colorName" type="text" class="form-control"
formControlName="colorName" name="colorName"/>
</div>
<button type="button" (click)="addCorlo()">ADD</button>
</form>
<ul>
<li *ngFor="let color of colorsList">{{ color.colorName }} <button (click)="delete()">DELETE</button></li>
</ul>
TS
import { Component, VERSION } from '@angular/core';
import { FormBuilder, FormGroup, FormArray, Validators } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Reactive Form';
colorsForm: FormGroup; // New Reactive Form
colorsList: any[] = [];
constructor(
private fb: FormBuilder
) { }
ngOnInit() {
this.colorsForm = this.fb.group({
colorName: [null]
});
}
addCorlo() {
if (this.colorsForm.valid) {
let color = {
colorName: this.colorsForm.value.colorName,
};
this.colorsList.push(color);
}
this.colorsForm.reset();
}
delete(){
console.log('delete')
}
}
我试图删除该元素,但 我没有成功.....
this is a stackblitz example ExampleLink
您将要计算ngFor中的索引:
将索引i向下传递给方法,然后根据该索引从数组中删除。
Here's a decent ref: https://www.angularjswiki.com/angular/how-to-get-index-of-element-in-ngfor-angular/
希望能有所帮助,
编码愉快!