这是代码:https ://stackblitz.com/edit/angular-gs8yo7?file=src/app/app.component.ts
HTML
<form nz-form [formGroup]="validateForm" (ngSubmit)="submitForm()">
<nz-form-item *ngFor="let control of listOfControl; let i = index">
<nz-form-label *ngIf="i == 0" [nzFor]="control.controlInstance">
<span translate>Project(s)</span>
</nz-form-label>
<nz-form-control [nzXs]="24">
<div nz-row nzGutter="8">
<div nz-col nzSpan="11">
<nz-select [formControlName]="project" name="projects" [attr.id]="control.id"
[nzPlaceHolder]="'Select Project(s)'">
<nz-option *ngFor="let item of project" [nzLabel]="item.description" [nzValue]="item.id">
</nz-option>
</nz-select>
</div>
<div nz-col nzSpan="11">
<nz-select formControlName="role" name="role" nzPlaceHolder="">
<nz-option *ngFor="let item of roles" [nzLabel]="item" [nzValue]="item"></nz-option>
</nz-select>
</div>
<div nz-col nzSpan="2">
<i nz-icon nzType="minus-circle-o" class="dynamic-delete-button"
(click)="removeField(control, $event)"></i>
</div>
</div>
</nz-form-control>
</nz-form-item>
<nz-form-item>
<nz-form-control>
<button nz-button nzType="dashed" class="add-button" (click)="addField($event)">
<i nz-icon nzType="plus"></i>
Add field
</button>
</nz-form-control>
</nz-form-item>
<nz-form-item>
<nz-form-control [nzXs]="{ span: 24, offset: 0 }" [nzSm]="{ span: 20, offset: 4 }">
<button nz-button nzType="primary">Submit</button>
</nz-form-control>
</nz-form-item>
</form>
TS
validateForm: FormGroup;
listOfControl: Array<{ id: number; controlInstance: string }> = [];
projects = [{
"id": "1ueI",
"description": "Project1"
},{
"id": "iqwu28",
"description": "Project2"
},{
"id": "1938qwe",
"description": "Project3"
}];
roles = ['ROLE_ADMIN', 'ROLE_USER'];
addField(e?: MouseEvent): void {
if (e) {
e.preventDefault();
}
const id = this.listOfControl.length > 0 ? this.listOfControl[this.listOfControl.length - 1].id + 1 : 0;
const control = {
id,
controlInstance: `passenger${id}`
};
const index = this.listOfControl.push(control);
console.log(this.listOfControl[this.listOfControl.length - 1]);
this.validateForm.addControl(
this.listOfControl[index - 1].controlInstance,
new FormControl(null, Validators.required)
);
}
removeField(i: { id: number; controlInstance: string }, e: MouseEvent): void {
e.preventDefault();
if (this.listOfControl.length > 1) {
const index = this.listOfControl.indexOf(i);
this.listOfControl.splice(index, 1);
console.log(this.listOfControl);
this.validateForm.removeControl(i.controlInstance);
}
}
submitForm(): void {
}
constructor(private fb: FormBuilder) {}
ngOnInit(): void {
this.validateForm = this.fb.group({});
this.addField();
}
我在这里要做的是,当它已经选择项目时,即使您添加新项目,它也应该删除。
并且何时提交应该是动态的。
[
{ id: projectId, role: role },
{ id: projectId, role: role },
]
喜欢
[{id: 1ueI, role: "ROLE_ADMIN" }, {id: 1938qwe, role: "ROLE_USER" }]
例如,当您选择 PROJECT 1 时,它将从列表下拉列表中,然后当您添加新项目时,它也应显示在列表中,它只会显示 PROJECT 2 和 PROJECT 3。