我试图做结构性的指令。我有复选框列表,当选中复选框时,我需要启用div,如果未选中复选框,我需要禁用div。
所以我尝试下面的代码,它成功启用,禁用div,但问题是我需要显示此div结束页面,但此指令创建/销毁复选框旁边的div。
我相信ViewContainerRef将复选框作为参考,它会在复选框旁边创建div。如何动态地为每个div提供viewcontainerref
import { Directive, TemplateRef, ViewContainerRef, Input, HostListener, HostBinding } from '@angular/core';
@Directive({
selector: '[showIfAdditional]'
})
export class ShowIfAdditionalDirective {
private component: any;
private tRef: TemplateRef<any>;
private opened: boolean;
constructor(public vcRef: ViewContainerRef) { }
@Input() set showIfAdditional(value: any) {
if (value !== this.component) {
this.component = value;
}
}
@Input('showIfAdditionalContent') set template(value: TemplateRef<any>) {
if (value !== this.tRef) {
this.tRef = value;
}
}
@HostListener('click') public onClick(): void {
this.toggle();
}
public toggle(): void {
if (this.opened) {
this.vcRef.clear();
} else {
this.vcRef.createEmbeddedView(this.tRef, { $implicit: this.component }); this.render();
}
this.opened = this.vcRef.length > 0;
}
}
HTML代码
<div #checkBoxDiv>
<mat-checkbox *ngFor="let list1 of componentsList1 [showIfAdditional]="list1.value" [showIfAdditionalContent]="expandRowDiv">
{{list1.value}}
</mat-checkbox>
<div>
<ng-template #expandRowDiv let-component>
<div style="overflow: hidden">
<h1>{{component|json}}</h1>
</div>
</ng-template>
所以上面的代码在下面的复选框旁边创建了破坏div
<div #checkBoxDiv>
[*] CHK1
dynamically_creatediv_comes_here
[] CHK2
[] CHK3
...
</div>
但是我需要在这个#checkboxDiv之外创建这个div,就像这样
<div #checkBoxDiv>
[*] CHK1
[] CHK2
[] CHK3
...
</div>
create_dynamically_div_here
请有人帮忙