0
我試圖創建一個負責呈現select
表單控件的Angular 2組件,並且在嘗試使其支持optgroup
時遇到了一些麻煩。在Angular 2中選擇支持optgroup的下拉組件
渲染時,我需要能夠在optgroup
和option
元素之間切換,具體取決於項目是否有子項。我試圖使用template
標記來迭代這些項目,但它看起來像在select
內不受支持。我也嘗試在相同的元素上添加*ngIf
和*ngFor
,但不支持。
如何在Angular 2中使用optgroup
創建select
?
形狀select.component.js
import { Component, Input, Output, EventEmitter, ElementRef } from '@angular/core';
import { CORE_DIRECTIVES, FORM_DIRECTIVES, NgClass, NgStyle } from '@angular/common';
export class FormSelectOption {
id: string;
text: string;
children: FormSelectOption[];
constructor(id: string, text: string, children: FormSelectOption[]) {
this.id = id;
this.text = text;
this.children = children;
}
}
@Component({
selector: 'form-select',
template: `
<select>
<!-- WORKING -->
<option *ngFor="let item of items" (click)="select(item.id)">{{item.text}}</option>
<!-- NOT WORKING -->
<!--<template *ngFor="let item of items">
<optgroup *ngIf="item.children" label="{{item.text}}">
<option *ngFor="let child of item.children" (click)="select(child.id)">{{child.text}}</option>
</optgroup>
<option *ngIf="!item.children" (click)="select(item.id)">{{item.text}}</option>
</template>-->
</select>
`
})
export class FormSelectComponent {
@Input()
items: FormSelectOption[];
@Input()
selectedValue: string[];
@Output()
valueChange: EventEmitter<any>;
constructor(private elementRef: ElementRef) {
this.valueChange = new EventEmitter<any>();
}
select(id) {
this.valueChange.emit(id);
}
}
app.ts
//our root app component
import {Component} from '@angular/core'
import {FormSelectComponent, FormSelectOption} from './form-select.component';
@Component({
selector: 'my-app',
template: `
<form-select [items]="things" [selectedValue]="selectedThing"></form-select>
`,
directives: [FormSelectComponent],
})
export class App {
selectedThing = '1';
things = [
new FormSelectOption('1', 'Fruit', [
new FormSelectOption('2', 'Bananas'),
new FormSelectOption('3', 'Apples'),
new FormSelectOption('4', 'Oranges')
]),
new FormSelectOption('5', 'Countries', [
new FormSelectOption('6', 'England'),
new FormSelectOption('7', 'New Zealand')
]),
new FormSelectOption('8', 'Shapes', [
new FormSelectOption('9', 'Square')
]),
];
}
urghh ......嗯,這是煩人。感謝堆! – ajbeaven
@yurzui我在同樣的情況下受到襲擊.....你的朋友不工作。你能否更新它 –
@PsycheGenie更新https://plnkr.co/edit/xYvGPAhFFpTCPcotqm9F?p=preview – yurzui