开发者

Angular - checkbox for string value of "true" or "false" gets checked always

I am working with an Angular application and getting data from a database. What gets returned is a string value, with different kinds of "values", some may be a string of JSON data, some may be just a string of texts, some is a string of boolean "true" or "false", however, it's still just a string.

And I have made changes so the type of input will change depending on what kind of string version it is.

for the "true" and "false", I made it so it now is a checkbox. The checkbox should be checked when it returns "true", and when unchecking, in the console, it now is a "false". But the checkbox is always checked

here are some code snippets

<input class="form-check"
       type="checkbox"
       *ngIf="isBoolValue"
       [(ngModel)]="model.value"
       ng-checked="isBoolValue" />

here I am using both a ngModel and a ng-checked, however, in the form, the only thing that works when submitting is ngModel, to make a change in the database from true to false. isBoolValue is just a boolean to check if this is true or false.

getDataById(id: string) {
  this.dataService.getDataById(id)
    .subscribe(result => {
      this.model = result;
      if (this.model.value === 'true'
        || this.model.value === 'false') {
        this.isBoolValue = true;
      }
   开发者_开发百科 });
}

Any idea how this could be done?

Make a checkbox unchecked if the string value is "false", right now it is always checked because its not true boolean value, just a string value with "true" or "false"


the issue come because isBoolValue is always set to true

an idea can be to cast the value return by your observable to a boolean and use it in the ng-checked

getDataById(id: string) {
  this.dataService.getDataById(id)
    .subscribe(result => {
      this.model = result;
      if (this.model.value === 'true'
        || this.model.value === 'false') {
        this.model.value = (this.model.value === 'true');
        this.isBoolValue = true;
      }
    });
}

<input class="form-check"
       type="checkbox"
       *ngIf="isBoolValue"
       [(ngModel)]="model.value"
       ng-checked="model.value" />
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜