2017-10-10 7 views
0

내가 좋아하는 컬렉션을 만들었습니다 그래서 (JSON에 해당) :동적 드롭 다운은 - AngularFire2

sports: { 
    football: { 
    name: 'football', 
    varieties: { 
     11aside: { 
     name: '11 a side' 
     }, 
     6aside: { 
     name: '6aside' 
     } 
    } 
    } 
} 

내가 지금처럼 선택 상자에서 다른 스포츠를 표시 할 수 있습니다 일단

// sports.controller.ts 
this.sports = db.collection('sports').valueChanges(); 

// sports.html 
<select formControlName="sport"> 
    <option value="">- Select -</option> 
    <option *ngFor="let sport of sports | async" [value]="sport.id">{{sport.name}}</option> 
</select> 

선택이 이루어졌으며 두 번째 선택 상자를 표시하고 사용자가 '다양성'을 선택하게합니다. anglefire2에서 이것을 달성하는 가장 좋은 방법은 무엇입니까?

도움 주셔서 감사합니다.

답변

0

이것이 왜 특히 anglefire2에 의존해야하는지 알 수 없습니다. 첫 번째 선택 드롭 다운 sport에 대한 formControl을 빈 문자열로 초기화했고 초기로드시 유효한 옵션으로 미리 선택되지 않았다고 가정합니다. 마찬가지로

this.form = this.formbuilder.group({ 
sport: '' 
}); 

템플릿의 값 변경 내용을 확인하여 해당 품종에 해당하는 두 번째 드롭 다운을 표시 할 수 있습니다.

선택한 값에 따라 어떤 주어진 순간에 품종의 값을 보유 할 수있는 '속성'을 가지고 가정, 구성 요소에 단순히이 추가 이제 첫 번째 선택 컨트롤의 값 변경에 대한

varieties: any[] = null; // declare varieties property in component 

this.form.get('sport').valueChanges 
    .subscribe((newVal) => { 
    if (!newval) { 
     this.varieties = null; 
    } else { 
     this.varieties = this.sports.filter((elem) => elem.id === newVal)[0].varieties; 
     // assuming each newVal is actually the property value of 'id' based on '[value]="sport.id"' <-- this assignment in the template 
    } 
    }); 

을 듣고 새로운 선택 드롭 다운뿐만 아니라 당신의 템플릿, 당신이 새로운 선택 드롭 다운에 할당 할 수있는 실제 value에 따라 코드를 수정해야 할 수도 있습니다, 심지어 품종 선택을 위해 새로운 formControl을 추가 할 수 있습니다

<select formControlName="sport"> 
    <option value="">- Select -</option> 
    <option *ngFor="let sport of sports | async" [value]="sport.id">{{sport.name}}</option> 
</select> 
<select *ngIf="varities"> 
    <option value="">- Select -</option> 
    <option *ngFor="let variety of varities" [value]="variety.name">{{variety.name}}</option> 
</select> 

. 희망이 도움이됩니다.

+0

도움 주셔서 감사합니다. 몇 가지 변경을해야했지만 꼭 올바른 방향으로 나를 가리키는 데 도움이되었습니다. 특히 양식 값에 valueChanges 함수를 사용하는 것이 좋습니다. –