首页 > 解决方案 > 如何向组件实例添加指令(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);
    }
}

标签: angulartypescriptcontrolvalueaccessor

解决方案


推荐阅读