问题
I am using angular2 cli and this is the way i have setup my form
In the component
export class UsersAddComponent implements OnInit {
ngOnInit() {
this.userForm = this._formBuilder.group({
role: ['', [Validators.required]],
others: this._formBuilder.array([]) //for adding multipe form inputs
});
this.addNewUser();
}
initAddress() {
return this._formBuilder.group({
sendcred: [''], //checkbox needs no validation in my logic
needs_reset: [''], // ''
.....other fields here
});
}
addNewUser() { //this is called whenever add new user button is clicked
const control = <FormArray>this.userForm.controls['others'];
const addrCtrl = this.initAddress();
control.push(addrCtrl);
}
In the html template am using primeng checkbox like this
<p-checkbox formControlName="needs_reset" label="User has to set password"
(onChange)="Onpwdchange()"></p-checkbox>
<p-checkbox formControlName="sendcred" name="send cred" label="Send user
login credentials " (onChange)="Oncredchange()"></p-checkbox>
The methods onpwdchange()
and oncredchange() just have a console.log("clicked")
Whenever i check the checkboxes am getting an error
this.model.push is not a function //i havent implemented push method anywhere
Ive checked on This primeng2 issue but they advice use of disableDeprecatedForms()
and provideForms()
which are not available in angular2 cli
How do i solve this issue
回答1:
- Initialize your form value as follows
file.ts
this.infraestructuraServiciosForm = this.fb.group({
....
complementarios : new FormControl('', []),
......
});
The following line avoids the error:
this.infraestructuraServiciosForm.controls['complementarios'].setValue([]);
file.html
<p-fieldset legend="Complementarios">
<body>
<div class="ui-g ui-fluid">
<div class="ui-g-12">
<div class="ui-g-3">
<p-checkbox name="cpl" value="acerasBordillos" label="Aceras y Bordillos" formControlName="complementarios" (onChange)="haCambiadoAcerasBordillos(checked)"></p-checkbox>
</div>
<div class="ui-g-3">
<p-checkbox name="cpl" value="soloBordillos" label="Solo Bordillos" formControlName="complementarios" (onChange)="haCambiadoSoloBordillos(checked)"></p-checkbox>
</div>
<div class="ui-g-3">
<p-checkbox name="cpl" value="telefonoFijo" label="Red de Teléfono Fijo" formControlName="complementarios"></p-checkbox>
</div>
<div class="ui-g-3">
<p-checkbox name="cpl" value="alumbradoPublico" label="Alumbrado Público" formControlName="complementarios"></p-checkbox>
</div>
</div>
</div>
</body>
</p-fieldset>
回答2:
According to PrimeNG documentation
https://www.primefaces.org/primeng/#/checkbox
formControlName doesnt work with primeNG's checkbox.
So you need to do like this
<p-checkbox value="xyz" [formControl]="myFormGroup.controls['name']"></p-checkbox>
if you want binary value true/false
<p-checkbox binary="true" [formControl]="myFormGroup.controls['name']"></p-checkbox>
来源:https://stackoverflow.com/questions/41929208/angular2-checkbox-with-primeng-fails