加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angular – 如何动态地将NG_VALUE_ACCESSOR组件添加到被动形式?

发布时间:2020-12-17 10:24:24 所属栏目:安全 来源:网络整理
导读:我们希望使用带有ComponentFactoryResolver和ViewContainerRef的自定义指令动态地将NG_VALUE_ACCESSOR组件添加到被动形式.问题是我们无法将formControlName分配给动态添加的组件,我们无法从组件中获取访问者值. 我们尝试了几种不同的选项,但它们都没有为我们
我们希望使用带有ComponentFactoryResolver和ViewContainerRef的自定义指令动态地将NG_VALUE_ACCESSOR组件添加到被动形式.问题是我们无法将formControlName分配给动态添加的组件,我们无法从组件中获取访问者值.

我们尝试了几种不同的选项,但它们都没有为我们工作(直接将formControlName添加到ngContainer会引发错误,也是ngComponentOutlet的一个选项,但是我们无法为组件提供参数).

我们在plunker中创建了一个静态测试用例(我们想要达到的结果)和一个使用指令的动态测试用例,我们无法将formControlName分配给组件.我们将在下面的评论中提供链接.

您可以尝试扩展NgControl.这是简单的实现.但它可能更复杂.

动态panel.directive.ts

@Directive({
    selector: '[dynamic-panel]'
})
export class DynamicPanelDirective extends NgControl implements OnInit  {

    name: string;

    component: ComponentRef<any>;

    @Output('ngModelChange') update = new EventEmitter();

    _control: FormControl;

    constructor(
        @Optional() @Host() @SkipSelf() private parent: ControlContainer,private resolver: ComponentFactoryResolver,private container: ViewContainerRef) {
        super();
    }

    ngOnInit() {
        let component = this.resolver.resolveComponentFactory<GeneralPanelComponent>(GeneralPanelComponent);
        this.name = 'general';
        this.component = this.container.createComponent(component);
        this.valueAccessor = this.component.instance;
        this._control = this.formDirective.addControl(this);
    }

    get path(): string[] {
        return [...this.parent.path !,this.name];
    }

    get formDirective(): any { return this.parent ? this.parent.formDirective : null; }

    get control(): FormControl { return this._control; }

    get validator(): ValidatorFn|null { return null; }

    get asyncValidator(): AsyncValidatorFn { return null; }

    viewToModelUpdate(newValue: any): void {
        this.update.emit(newValue);
    }

    ngOnDestroy(): void {
        if (this.formDirective) {
            this.formDirective.removeControl(this);
        }
        if(this.component) {
            this.component.destroy();
        }
    }
}

Modified Plunker

所以

How to dynamically add NG_VALUE_ACCESSOR component to reactive form?

this.valueAccessor = this.component.instance;

在我的情况下

如果您想使用验证器,请参阅此Plunker

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读