Angular "select" binding to a true/false value not working

3.5k views Asked by At

I'm trying to bind my select element to a true/false value. The binding seems to happen as the -- select -- option isn't shown, meaning Angular knows there's a value, but the display is just blank by default. If I click on it then I see my Yes and No choices, but it's not being initially set.

        <select class="form-control" id="primary" name="primary" required
                [(ngModel)]="primaryValue">
            <option *ngIf="primaryValue === null" [ngValue]="null">-- Select --</option>
            <option [ngValue]="true">Yes</option>
            <option [ngValue]="false">No</option>
        </select>

The primaryValue is defined like this in the typescript file:

@Input() primaryValue: boolean;

If I do this with just an input it works fine, but if I use primaryValue as both input and output, then it doesn't work. You can see an example on StackBlitz

3

There are 3 answers

0
Gargoyle On BEST ANSWER

Finally tracked this down. In the component that showed the questions I had this as part of the @Component definition:

viewProviders: [  // This makes the whole child participate in the parent's form validation
    {
        provide: ControlContainer,
        useExisting: NgForm
    }
]

which I had seen on the web say that it makes the child controller's components be part of the parent component's form validation. As soon as I removed that part, everything started working properly.

0
Sunil Singh On

You must pass the boolean value to set the initial value.

<app-lab-hazard-classification-question-group 
    (change)="onHazardValueChanged($event)"
    primaryQuestion="Primary Question One"
    [primaryValue]="true"                         <!-- Set the boolean value -->
    secondaryQuestion="Secondary Question One" 
    [secondaryValue]="false">                     <!-- Set the boolean value -->
</app-lab-hazard-classification-question-group>

Working copy is here - https://stackblitz.com/edit/angular-5mdctu

0
Shivam Sinha On

Two-Way binding is also called as "Banana in a box" binding i.e. [()].

Inside your AppComponent.html, reverse the order of parenthesis for correct binding

<app-question-group [(primaryValue)]="valueOne"></app-question-group>