I noticed I must use [value]=true as opposed to value = true in order for my radio button to get the initial value from the component class. How is this working - does putting brackets around value somehow tell Angular to use the initial value from [(ngModel)]?
HTML:
<input type="radio" id ="yesChoice" [(ngModel)] ="serverDeluxe" [value]=true >
<label for="yesChoice">Yes</label>
<br>
<input type="radio" id ="noChoice" [(ngModel)] ="serverDeluxe" [value]=false >
<label for="noChoice">No</label>
TS:
export class ServerComponent implements OnInit{
serverId = 10;
serverStatus = 'offline';
serverDeluxe = true;
ngOnInit(): void {
}
getServerStatus(): string{
return this.serverStatus;
}
}
As explained in the Angular documentation:
The brackets,
[], tell Angular to evaluate the template expression. If you omit the brackets, Angular treats the string as a constant and initializes the target property with that string:<app-item-detail childItem="parentItem"></app-item-detail>Omitting the brackets will render the string
"parentItem", not the value ofparentItem.
In your case, the brackets allow to set the radio input to a boolean value:
[value]="true" <---- Sets the value to the boolean true
value="true" <---- Sets the value to the string "true"
The initial value of serverDeluxe is bound to the control with [ngModel] (which is a part of [(ngModel)]). Since serverDeluxe is a boolean property, it will never match the string "true" or "false".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With