I am using Angular7 mat-checkbox with reactive forms. Below is the code.
shared: FormGroup;
constructor(private router: Router, fb: FormBuilder,private filterServices:FilterServices) {
this.shared = fb.group({
"byAll": false,
"byFriends": false,
"byPeers": false,
"byExperts": false,
"bySpecificFriends": false,
"byNone":false,
"permissionType":"share",
"emails": []
});
}
On nginit function i am getting data from db as shown below
ngOnInit(){
this.filterServices.getFilters(12).subscribe((res)=>{
console.log(res);
this.setFormvalues(res);
})
}
setFormvalues(response:any){
response.forEach(element => {
this.sharedEmails = [];
this.sharedEmails = element['emails'].split(',');
this.shared.value['byAll'] = element["byAll"]
this.shared.value['byExperts'] = element['byExperts']
this.shared.value['byFriends'] = element['byFriends']
this.shared.value['byNone'] = element['byNone']
this.shared.value['byPeers'] = element['byPeers']
this.shared.value['bySpecificFriends'] = element['bySpecificFriends']
console.log(this.shared)
})
}
I am able to set the data to the properties in shared object, but checkboxes in html is not getting checked. Suppose shared['byAll'] was initially false (checkbox initially unchecked),but after getting data fro service calls now its value is true. But in html its not getting reflected i mean checkbox is not getting checked. Am i going wrong somewhere??
below is the html code.
<form [formGroup]="shared">
<div fxLayout="row" fxLayoutGap="20px">
<mat-checkbox formControlName="byAll">All</mat-checkbox>
</div>
</form>
尝试这个
this.shared.value['byAll'].setValue(element["byAll"]);
I got the solution!
We can use patchValue if we are updating only few values,else if we want to update all the values in a form group then use setValue.
patch value format
this.shared.patchValue({
"key":"value"
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.