I am new to angular. I am trying to show radio buttons (checked and unchecked) based on the server response, checked attribute is not working.
I am trying to show two radio buttons for one label.one radio button is “Allow” and other radio button is “Deny”. Server response be like { “math”: true , “science”: false ,”language” : true}.I need to show ‘Allow’ radio button should be checked for all true values and ‘Deny’ button should be checked for false value. This what I am trying
radio-button.component.html
<form [formGroup]= subjectGroup (ngsubmit)="onSubmit()">
<div class="form-group row">
<label for="maths" class="col-sm-4 col-form-label text-dark">
<b>Maths</b></label>
<div class="form-check form-check-inline">
<input id="allow" type="radio" value="allow" name="screenCapture" formControlName="mathsValue"(click)="changeValue('maths', true)" checked="'response.maths' == true">
<label for="allow">Allow</label>
</div>
<div class="form-check form-check-inline">
<input id="deny" type="radio" value="deny" name="screenCapture" formControlName="mathsValue" (click)="changeValue('maths', false)"
checked="'response.maths' == false">
<label for="deny">Deny</label>
</div>
</div>
<button class="btn btn-success>Update</button>
radio-button.component.ts
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-radio-button',
templateUrl: './radio-button.component.html',
styleUrls: ['./radio-button.component.css']
})
export class RadioButtonComponent implements OnInit {
public response;
public subjectGroup: FormGroup;
ngOnInit(): void {
this.getResponse();
this.form();
}
getResoponse(){
// In this method, I am Storing all the server Response data to global variable (response)
}
form(){
this.subjectGroup = this.fb.group({
maths: new FormControl('')
})
changeValue(e, value) {
(this.response[e]) = value
}
}
I want to checked allow button to all true values and to checked deny button for all false values, can anyone share the code snippets for this functionality in angular
Your example shows checked="'response.maths' == true"
.
I suspect if you inspect your DOM, your element will literally have this string in place. If you want angular to evaluate that as an actual code expression, you either need to use [checked]
or {{'response.maths' == true}}
.
For your usage, neither will actually work, because you’re checking that the string 'response.maths'
is true, which it isn’t. (Though you’re doing ==
rather than ===
so the whole truthy thing with JS means it probably is true).
What you want to use is much simpler: [checked]="response.maths"
.
response.maths
IS a boolean value, so you can just use it directly.