Angular Radio Button Binding using true false value

Viewed 2579

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;
  }
}
2 Answers

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 of parentItem.

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".

The above code is working for you because of [value] property. It treats the value as a dynamic value(as template expression) hence html is able to bind the radio option.

If we will provide value=true instead of [value]=true then we will have to provide name property.

For value=true it will take as value="true" and for [value]=true as value=true

Related