我正在尝试编写一个自定义指令,如果用户在下拉列表中选择" all“选项,它会自动选择我能够获得的自定义指令中的所有选项,以选择所有选项,但这不会更新消费组件上的模型。
自定义指令
@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并在框语法中使用香蕉来尝试更新模型,但没有成功。
我可以使用@Output并发出消费组件可以处理的事件,类似于https://toddmotto.com/component-events-event-emitter-output-angular-2,但我更希望能够简单地自动更新模型。
我想知道有没有可能?或者,如果创建类似于http://plnkr.co/edit/ORBXA59mNeaidQCLa5x2?p=preview的自定义组件是更好的选择。
提前感谢
发布于 2016-08-23 22:52:34
在Javascript中设置选中状态不会在选择组件上发送"changed“事件(可能是因为它直接访问子选项,但不确定)。尝试通过执行以下操作自己触发更改的事件:
if (this.selectElement.options[0].selected) {
for (let i = 0; i < this.selectElement.options.length; i++) {
this.selectElement.options[i].selected = true;
}
//These are the two new lines
let changeEvent = new Event("change", {"bubbles":true, "cancelable": false});
this.selectElement.dispatchEvent(changeEvent);
}看看这是否会触发ngModel进行更新。
https://stackoverflow.com/questions/39100178
复制相似问题