angular - 如何向组件实例添加指令(formControlName)?
问题描述
我尝试使用表单支持动态创建输入表单。它工作得很好,因为我可以直接在 html 元素上添加指令“formControlName”。
但是现在我不知道如何将指令设置为动态创建的组件的实例,而不是 ng 模板。
指令 myCustomComponentDirective 通过给定的类型(使用 ComponentFactoryResolver)创建一个组件并将其渲染到 ng 模板中。CustomComponent 实现 controlValueAccessor 并在 formControlName 指令直接标记在其上时工作。
如何在指令 myCustomComponentDirective 中动态添加类似“formControlName”的指令?
组件.html:
<form [formGroup]="formGroup">
<ng-container *ngFor="let singleForm of formConfigs;">
<ng-container [ngSwitch]="singleForm?.type">
<ng-container *ngSwitchCase="'input'">
<input formControlName="singleForm.conrolName" >
</ng-container>
<ng-container *ngSwitchCase="'custom'">
<!-- next line will not working since ng-template hasnt a nativeElement property -->
<!-- <ng-template myCustomComponentDirective formControlName="singleForm.conrolName"></ng-template> -->
<div myCustomComponentDirective formControlName="singleForm.conrolName"></div>
</ng-container>
</ng-container>
</ng-container>
我要设置 formControlName 的指令:
Directive({
selector: '[customComponentDirective]',
})
export class ComponentDirective implements OnInit
{
@Input() customComponentDirective: Type<any>;
constructor(private _viewContainerRef: ViewContainerRef,
private _componentFactoryResolver: ComponentFactoryResolver){}
private _appendDirective(){
// here i want to add the directive when the component has been created....
mycreatedInstace.addDirective(formControlName);
}
}
解决方案
推荐阅读
- docker - 将keycloak docker镜像部署到heroku
- apex - 我面临关于顶点图像加载的错误
- reactjs - 类型 '"#e21c1a"' 不可分配给类型 'undefined'。在反应类型脚本中
- jquery - 从您离开的地方显示课程内容
- python - 如何根据列组合对行进行排序 - python
- python - 通过匹配列值更新 DataFrame 索引
- javascript - 如果在 JQuery 模式对话框上单击转义键,如何将用户发送到主页
- split - 无法从拆分和空白修剪中获取数据
- php - 我正在尝试在 wordpress 中制作插件,但 php echo 没有解析 html 标签
- visual-studio-code - 如何在 Visual Studio Code 中同时启用 FiraCode 连字和样式集?