Angular 7 Mat-复选框未使用反应形式进行检查

时间:2019-04-03 11:17:26

标签: angular

我正在将Angular7 mat-checkbox与反应形式一起使用。下面是代码。

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": []
        });
}

在nginit函数上,我正在从db获取数据,如下所示

  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)
       })
}  

我能够将数据设置为共享库中的属性,但是未选中html中的复选框。假设shared ['byAll']最初为false(最初未选中该复选框),但是在通过服务调用获取数据后,现在其值为true。但是在html中,它没有得到反映,我的意思是复选框未被选中。我在哪里出错了?

下面是html代码。

<form [formGroup]="shared">
                        <div fxLayout="row" fxLayoutGap="20px">
                            <mat-checkbox formControlName="byAll">All</mat-checkbox>
</div>
</form>

2 个答案:

答案 0 :(得分:0)

尝试一下

this.shared.value['byAll'].setValue(element["byAll"]);

答案 1 :(得分:0)

我知道了!

如果只更新几个值,则可以使用patchValue;否则,如果要更新表单组中的所有值,则可以使用setValue。

补丁值格式

if (document.getElementById('theme')) {
  if (localStorage) {
    // console.log('storidge');
    if (!localStorage.getItem('theme')) {
      localStorage.setItem('theme', 'dark');
    } else {
      if (localStorage.getItem('theme') == 'dark') {
        $("link[id='theme']").attr('href', '/static/css/dark.css');
      } else if (localStorage.getItem('theme') == 'light') {
        $("link[id='theme']").attr('href', '/static/css/light.css');
      }
    }
  }
}

$('#toggle-theme').click(function() {
  if ($("link[id='theme']").attr('href') == '/static/css/dark.css') {
    $("link[id='theme']").attr('href', '/static/css/light.css');
    localStorage.setItem('theme', 'light');
    console.log('changed to light.css');
  } else {
    $("link[id='theme']").attr('href', '/static/css/dark.css');
    localStorage.setItem('theme', 'dark');
    console.log('changed to dark.css');
  }
});