问题
I have a Model driven form and want to show the fields based on radio input. Code :-
<div class="form-group">
<md-radio-group class="form-control" id="radio1" formControlName="selection">
<md-radio-button [value]="A" >A</md-radio-button>
<md-radio-button [value]="B">B</md-radio-button>
</md-radio-group>
</div>
<div class="form-group" *ngIf="selection.value=='A'">
<md-input-container>
<textarea md-input placeholder="A" class="form-control"
formControlName="A"
style="border:none;"></textarea>
</md-input-container>
</div>
<div class="form-group" *ngIf="selection.value=='B'">
<md-input-container>
<input md-input placeholder="B" class="form-control"
formControlName="B"
style="border:none;">
</md-input-container>
</div>
Getting error as "Cannot read property 'value' of undefined" As no radio is selected.
How can I specify to select the first one as default.
回答1:
You need to pass a string
as a value for the radio. Right now Angular tries to find a variable with the name A
.
<md-radio-group class="form-control" [(ngModel)]="selection.value"
id="radio1" formControlName="selection">
<md-radio-button [value]="'A'">A</md-radio-button>
<md-radio-button [value]="'B'">B</md-radio-button>
</md-radio-group>
You initialize the radio as you assign a value to selection.value
in the according component:
class MyRadioComponent {
selection = {"value":"A"};
}
回答2:
Try this:
this.complexForm = fb.group({
'name': [null, Validators.required],
'description': [null, Validators.required],
'file': ["A", Validators.required],
});
回答3:
You are getting this error because selection
formControl is not yet created.There are two possible solution for this.
Use safe navigation operator (
?.
) as*ngIf=selection?.value=='A'
while accessing the value of radio.<div class="form-group" *ngIf="selection?.value=='A'"> <md-input-container> <textarea md-input placeholder="A" class="form-control" formControlName="A" style="border:none;"></textarea> </md-input-container> </div>
Prepare your form before the view is rendered.(i.e prepare your form in constructor of the component.)
and default value to any form control can be given when we create the form control.
for example in your case you can set default value of selection
form control as follows.
let myForm = new FormGroup({ selection : new FormControl('A') })
来源:https://stackoverflow.com/questions/41558196/how-can-we-set-the-default-value-of-radio-button-in-angular-2