kav,在自定义表单控件中,
registerOnChange(fn: (v: any) => void) {
this.formGroup.valueChanges.subscribe(fn);
}
所以,组件返回formgroup的“value”。由于控件被禁用,该值不返回此字段。可以更改CustomControl以返回FormGroup的rawValue,因此需要创建onChangeFunction,并在nGoninit中订阅更改并发送rawValues。在订阅时,最好使用takewhile和变量取消订阅
export class DetailsFields implements ControlValueAccessor,OnInit,OnDestroy {
...
onChange: (v:any) => void = () => {}; //<--define a function
isAlive:boolean=true; //<--use to unsubscribe, see below
registerOnChange(fn: (v: any) => void) {
this.onChange = fn; //<--equal to function
}
//In ngOnInit
ngOnInit()
{
this.formGroup.valueChanges.pipe(takeWhile(()=>this.isAlive))
.subscribe(v=>{
//return this.formGroup.getRawValue()
this.onChange(this.formGroup.getRawValue())
})
}
//In ngOnDestroy
ngOnDestroy() { //make isAlive=False to unsubscribe
this.isAlive=false;
}
但在这种情况下,您收到的年份总是启用或不启用
还有另一个问题,那就是没有定制的表单控件,只是管理品牌、年份和颜色的组件。为此,第一个方法是更改应用程序组件,并像使用表单阵列创建另一个表单一样创建表单。
<div id="cars" [formGroup]="form">
<div formArrayName="cars">
<div *ngFor="let car of form.get('cars').controls; let i = index;"
[formGroupName]="i">
<app-details-fields [formGroup]="form.get('cars').at(i)" ></app-details-fields>
</div>
</div>
</div>
在formray中,我们迭代form.get(“cars”).controls,我们需要放置一个[formGroupName]=“i”。在组件中,只需作为输入[FormGroup]Form.get(“cars”)传递到(i)
当然,您需要更改函数“createCars”以返回一个formGroup。不是返回对象类型make:…,color:…,year的FormControl
createCar(car: any) { //return a formGroup,not a formControl
return this.builder.group({
make: car.make,
color: car.color,
year: car.year
});
}
嗯,细节字段变得更容易:
详细信息-fields.component.ts
@Component({
selector: 'app-details-fields',
templateUrl: './details-fields.component.html',
styleUrls: ['./details-fields.component.css'] ,
})
export class DetailsFields {
@Input() formGroup:FormGroup
disableYear() {
this.formGroup.get('year').disable();
}
enableYear() {
this.formGroup.get('year').enable();
}
}
详细信息-fields.component.html
<div [formGroup]="formGroup">
<div class="car-wrap">
<div>
<p class="title">This car is a {{formGroup.get('make').value}}</p>
<div>
<input type="text" formControlName="make">
<input type="number" formControlName="year">
<input type="text" formControlName="color">
</div>
<div>
<button style="margin-top: 3px;" (click)="enableYear()">Enable year</button>
<button style="margin-top: 3px;" (click)="disableYear()">Disable year</button>
</div>
</div>
</div>
</div>