我是Angular的初学者。我正在尝试按字母顺序对下拉列表FormArray进行排序。
component.html
<label
class="custom-control custom-checkbox"
*ngFor="let car of carsControls; let i = index"
[hidden]="!cars[i]?.show">
<input type="checkbox" class="custom-control-input" [formControl]="car" />
<span class="custom-control-label" [innerHTML]="cars[i]?.name"></span>
</label>
组件.ts
ngOnInit() {
this.cars.sort((a, b) => a.name.localeCompare(b.name));
}
这会对下拉列表的标签进行排序,但不会对carsControl进行排序。所以它不能正常工作。我不知道如何按字母顺序排列AbstractControl。还是我必须对汽车进行FormGroup排序?
编辑:
我得到这样的控制:
get carsControls() {
return (this.carFormGroup?.get('cars') as
FormArray)?.controls;
}
FormGroup:
carFormGroup = this.formBuilder.group({
filter: [''],
cars: this.formBuilder.array([])
如果我能了解您如何定义carsControls
变量和cars
变量,使我的答案更加完整,那将非常有帮助。
我会使用Object.keys
从FormGroup
中获取每个控件名称并对它们进行排序。然后我会在模板中迭代它们。
app.component.ts:
export class AppComponent {
myForm: FormGroup;
get controls(){
//Object.keys() will return each form control name
//Then sort them alphabetically
return Object.keys(this.myForm.controls).sort();
}
constructor(private fb: FormBuilder){}
ngOnInit(){
//Define my form - note how they're not alphabetical
this.myForm = this.fb.group({
"car": new FormControl(false),
"dinosaur": new FormControl(false),
"ant": new FormControl(false)
});
}
}
app.component.html:
<!-- The controls must live inside a form -->
<form [formGroup]="myForm">
enter code here
<!-- iterate each control name -->
<div *ngFor="let ctrl of controls">
<!-- Use any kind of input you want here! -->
<input type="checkbox" [formControlName]="ctrl">
<label>{{ctrl}}</label>
</div>
</form>
下面是一个stackblitz演示它是如何工作的。