一般这部分代码放在xx.component.html,会自动编译成页面
<nz-row nzGutter="15">
<nz-col [nzSpan]="6">
<nz-select [(ngModel)]="formData.field102" nzPlaceHolder="请选择下拉选择" [ngStyle]="{'width': '100%'}">
<nz-option *ngFor="let item of selectOptions; index as index" [nzLabel]="item.label"
[nzValue]="item.value" [nzDisabled]="item.disabled"></nz-option>
</nz-select>
</nz-col>
<nz-col [nzSpan]="6">
<nz-date-picker [ngStyle]="{'width': '100%'}" nzPlaceHolder="请选择日期选择" [nzAllowClear]="false"
(ngModelChange)="datePickChange()"></nz-date-picker>
</nz-col>
<nz-col [nzSpan]="4">
<button nzType="primary" nz-button nzSize="medium">主要按钮</button>
</nz-col>
</nz-row>
但现在是js内处理完的代码就是上面这些,如何才能渲染/加载到页面上呢
###看描述你应该是想在运行时,动态的组装和插入视图模板。并使它能够渲染和执行数据绑定。
这个跟 ng-zorro 组件库本身没有关系。可以使用compiler.compileModuleAndAllComponentsAsync
动态创建组件来实现,毕竟,组件和模块也不过是装饰器修饰的类而已,而装饰器本身也就是个函数。
代码大概思路是:
创建一个负责动态生成组件的函数:
let temple = `<div style="border: 1px solid blue; margin: 5px; padding: 5px">
<h4>动态插入字符串组件 </h4>
<h5>绑定值: {{data.some}}</h5>
<h4>显示 zorro 组件</h4>
<nz-row nzGutter="15">
<nz-col [nzSpan]="4">
<button nzType="primary" nz-button nzSize="medium">主要按钮</button>
</nz-col>
</nz-row>
</div>`
动态的创建组件,并插入 <div #vc>
位置
@Component({
selector: 'dynamic-example',
template: `<h2>下面是动态组装部分<h2>
<div #vc></div>`
})
export class DynamicTemplateComponent {
@ViewChild('vc', { read: ViewContainerRef }) vc?: ViewContainerRef;
private cmpRef?: ComponentRef<any>;
// 注入依赖
constructor(
private compiler: Compiler,
private injector: Injector,
private moduleRef: NgModuleRef<any>,
) { }
ngAfterViewInit() {
// 使用字符串模板创建组件
const tmpCmp = Component({ template })(class {
data = {
some: '123'
};
});
// 同时也需要为这个组件创建动态的模块
// 注意引入需要的 zorro 模块
const tmpModule = NgModule({
imports: [
CommonModule,
NzGridModule,
NzButtonModule
],
declarations: [tmpCmp]
})(class { });
this.compiler.compileModuleAndAllComponentsAsync(tmpModule)
.then((factories) => {
const f = factories.componentFactories[0];
this.cmpRef = f.create(this.injector, [], null, this.moduleRef);
this.cmpRef.instance.name = 'my-dynamic-component';
this.vc?.insert(this.cmpRef.hostView);
});
}
}
测试效果如下:
代码示例:Github