简体   繁体   中英

initializing and getting a radio button value on component

Question: How can I get value of radio input on component initialization in this scenario?

Component:

colors = ['red', 'blue'];
selectedColor: FormControl;

ngOnInit() {
    this.selectedColor = new FormControl();
}
ngAfterViewChecked() {
    console.log(this.selectedColor.value) // return null on component initialazation
}

Template:

<ng-container *ngFor="let c of colors,  let i = index">
  <input
    [formControl]="selectedColor"
    type="radio"
    name="group"
    [id]="c"
    [value]="c"
    [checked]= "i === 0">
  <label attr.for="{{c}}">{{c}}</label>
</ng-container>

Now if I try to get value of checked input in ngAfterViewChecked() which is the input that has a "i === 0" condition equal to true, I get null on component initialization but it return correct value on radio input changes.

<input
    type="checkbox"
    class="form-control"
    id="'someRandomId'"
    name="'someRandomId'"
    [ngModel]="value"
    (ngModelChange)="changeValue()">
  <label  [attr.for]="'someRandomId'"><span *ngIf="name">{{name}}</span></label>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM