2

我从事 angular 4 项目。
在这个项目中,我需要将第一个选项设置为选择列表中的默认选项。
但是问题是这个选择框在一个子组件下,并且这个选择框的数据是从父组件传递过来的。
为了更好地理解代码如下:

父组件html:

<serviceSelect [services]="services"></serviceSelect>

子组件html:

<select [(ngModel)]="selectedServiceType" [ngModelOptions]="{standalone: true}" (ngModelChange)="getServiceType($event)">
   <ng-container *ngFor="let service of settings?.service_type">
       <option [ngValue]="service">{{service.name}}</option>
   </ng-container>
</select>

子组件 .ts 代码:

import { Component, Input, Output, EventEmitter, OnInit } from '@angular/core';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import { FormBuilder, FormGroup, Validators, FormArray, FormControl } from '@angular/forms';

@Component({
   selector: 'serviceSelect',
   templateUrl: './serviceSelect.component.html',
   styleUrls: ['./serviceSelect.component.scss']
})
export class serviceSelectComponent {
      @Input() services : any;
      selectedServiceType: any;

      getServiceType(event) {
        this.selectedServiceType = event;
      }
}

我们无权访问ngOnInitor中的 services 变量ngAfterViewInit
我试图通过这些函数设置默认值。如果有任何其他建议如何将第一个选项作为默认选项,请告诉我。

4

0 回答 0