gpt4 book ai didi

Angular 2动态双向绑定(bind)

转载 作者:太空狗 更新时间:2023-10-29 17:32:10 24 4
gpt4 key购买 nike

我正在尝试构建一个动态附加另一个组件的组件。作为示例,这里是我的父类:

import { Component, ComponentRef, ViewChild, ViewContainerRef, ComponentFactoryResolver } from '@angular/core';

@Component({
templateUrl: './app/sample-component.component.html',
selector: 'sample-component'
})
export class SampleComponent {

@ViewChild('dynamicContent', { read: ViewContainerRef })
protected dynamicComponentTarget: ViewContainerRef;
private currentComponent: ComponentRef<any>;
private selectedValue: any;

constructor(private componentResolver: ComponentFactoryResolver) {

}

private appendComponent(componentType: any) {
var factory = this.componentResolver.resolveComponentFactory(componentType);
this.currentComponent = this.dynamicComponentTarget.createComponent(factory);
}
}

sample-component.component.html:

<div #dynamicContent></div>

它可以很好地附加一个元素,但我不知道如何动态绑定(bind)双向,就像我在静态组件中所做的那样:[(ngModel)]="selectedValue"

最佳答案

不支持绑定(bind)动态添加的组件。

您可以使用共享服务与动态添加的组件进行通信 ( https://angular.io/docs/ts/latest/cookbook/component-communication.html )
或者您可以使用 this.currentComponent 引用强制读取/设置:

private appendComponent(componentType: any) {
var factory = this.componentResolver.resolveComponentFactory(componentType);
this.currentComponent = this.dynamicComponentTarget.createComponent(factory);
this.currentComponent.instance.value = this.selectedValue;
this.currentComponent.instance.valueChange.subscribe(val => this.selectedValue = val);
}

关于Angular 2动态双向绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39951686/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com