这是html文件中的代码:
<div class="form-group">
<div class="form-text">Some Question about Email and Phone Details?</div>
<div>
<input type="radio" value="1" [formControl]="signUpDetailsForm.controls['details']" name="details" (click)="EmailClicked()"
ng-model="selectedOption"> Email</div>
<div>
Run Code Online (Sandbox Code Playgroud)
文字两者
在component.ts类中,我将selectedOption设置为1.像这样:
export class TestComponent implements OnInit{
signUpDetailsForm: FormGroup;
public submitted : boolean;
public selectedOption : string ='1';
Run Code Online (Sandbox Code Playgroud)
我可以看到selectedOption值设置正确,如在ngOnInit中,值打印为1:
ngOnInit() {
console.log('selectedOption='+this.selectedOption);
}
Run Code Online (Sandbox Code Playgroud)
我还试过另一种方法来解决这个问题,方法是在ng-init中设置selectedOption,但仍然不起作用.
<div ng-init="selectedOption=1">
<div>
<input type="radio" value="1" [formControl]="signUpDetailsForm.controls['details']" name="details" (click)="EmailClicked()"
ng-model="selectedOption"> Email</div>
<div>
<input type="radio" value="2" ng-model="selectedOption" [formControl]="signUpDetailsForm.controls['details']" name="details" (click)="PhoneClicked()"> Text</div>
<div>
<input type="radio" value="3" ng-model="selectedOption" [formControl]="signUpDetailsForm.controls['details']" name="details" (click)="BothClicked()"> Both</div>
</div>
Run Code Online (Sandbox Code Playgroud)
UPDATE
我更新的代码看起来像这样,默认情况下仍然没有选择收音机:
<div class="form-group">
<div class="form-text">Some Question about Email and Phone Details?</div>
<div>
<input type="radio" value="1" [formControl]="signUpDetailsForm.controls['details']" name="details" (click)="EmailClicked()"
[(ngModel)]="selectedOption"> Email</div>
<div>
<input type="radio" value="2" ng-model="selectedOption" [formControl]="signUpDetailsForm.controls['details']" name="details" (click)="PhoneClicked()"> Text</div>
<div>
<input type="radio" value="3" ng-model="selectedOption" [formControl]="signUpDetailsForm.controls['details']" name="details" (click)="BothClicked()"> Both</div>
</div>
Run Code Online (Sandbox Code Playgroud)
//这是在component.ts类中:
public selectedOption :string;
ngOnInit() {
this.selectedOption="1";
}
Run Code Online (Sandbox Code Playgroud)
从威廉的评论中得到了暗示.回答贴在这里:
@Component({
selector: 'my-app',
template: `
<form>
<div class="container">
<div class="row">
<div class="col-md-2"></div>
<header class="header col-md-8">
<div class="form-group">
<div class="form-text">Some Question about Email and Phone Details?</div>
<div>
<input type="radio" [value]="1" name="details" [(ngModel)]="selectedOption">
Email</div>
<div>
<input type="radio" [value]="2" name="details" [(ngModel)]="selectedOption"> Text</div>
<div>
<input type="radio" [value]="3" name="details" [(ngModel)]="selectedOption"> Both</div>
</div>
</header>
</div>
</div>
</form>
`,
})
export class App {
public selectedOption :number =3;
constructor() {
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7205 次 |
| 最近记录: |