【发布时间】:2016-08-23 11:40:04
【问题描述】:
我正在尝试编写一个自定义指令,如果用户在下拉菜单中选择“全部”选项,它会自动选择所有选项我能够让我的自定义指令选择所有选项,但这不会更新消费组件上的模型。
自定义指令
@Directive({ selector: '[selectAll]' })
export class SelectAllDirective {
private selectElement: any;
private selectedItemsd:number[];
constructor(private el: ElementRef) {
this.selectElement = el.nativeElement;
}
@HostListener('change')
onChange() {
if (this.selectElement.options[0].selected) {
for (let i = 0; i < this.selectElement.options.length; i++) {
this.selectElement.options[i].selected = true;
}
}
}
}
还有模板
<select selectAll multiple
ngControl="shoreLocation"
#shoreLocation="ngModel"
id="shoreLocation"
[(ngModel)]="customTask.shoreLocations"
name="shoreLocation"
class="form-control multi-select"
required
style="height:150px">
我已经尝试创建一个@Input 并使用 box 语法中的香蕉来尝试更新模型,但没有成功。
我能够使用@Output 并发出消费组件可以处理的事件,类似于https://toddmotto.com/component-events-event-emitter-output-angular-2,但如果我可以简单地自动更新模型,我更愿意。
我想知道它是否可能?或者,如果创建类似于 http://plnkr.co/edit/ORBXA59mNeaidQCLa5x2?p=preview 的自定义组件是更好的选择。
提前致谢
【问题讨论】:
标签: javascript angular angularjs-directive