是否有一种方法可用于在动态创建的Angular 2组件上定义@Input属性?
我正在使用ComponentFactoryResolver在容器组件中创建组件.例如:
let componentFactory = this.componentFactoryResolver.resolveComponentFactory(componentName);
let componentRef = entryPoint.createComponent(componentFactory);
Run Code Online (Sandbox Code Playgroud)
其中"entryPoint"在组件HTML中是这样的:
<div #entryPoint></div>
Run Code Online (Sandbox Code Playgroud)
并在我的容器组件中定义:
@ViewChild('entryPoint', { read: ViewContainerRef } entryPoint: ViewContainerRef;
Run Code Online (Sandbox Code Playgroud)
这很好用,但我找不到让@Input属性在新创建的组件上工作的方法.我知道您可以在组件类上显式设置公共属性,但这似乎不适用于ng-reflect.在进行此更改之前,我有一个"选定"属性,用"@Input()"装饰,导致Angular将以下内容添加到DOM:
<my-component ng-reflected-selected="true"></my-component>
Run Code Online (Sandbox Code Playgroud)
有了这个,我就能够动态更新标记来切换CSS类:
<div class="header" [class.active-header]="selected === true"></div>
Run Code Online (Sandbox Code Playgroud)
根据一些搜索,我能够找到一种方法使"@Output"按预期工作,但我还没有为@Input找到任何东西.
让我知道是否有其他背景会有所帮助,我很乐意添加它.
通过ComponentFactory动态创建组件时,返回的ComponentRef提供了一个destroy方法,它完全适用于我想要完成的任务.考虑到这一点,看起来我需要做的就是为静态创建的组件获取ComponentRef,然后使用其destroy函数(这个答案说明),但是当我尝试这个时,我得到一个错误,说"destroy是不是一个功能"即使我确实得到了一个对象.
这是我用于ViewChild的语法:
@ViewChild(MyComponent) myComponentRef: ComponentRef<MyComponent>;
Run Code Online (Sandbox Code Playgroud)
而我的"破坏"电话:
private destroy() {
this.myComponentRef.destroy();
}
Run Code Online (Sandbox Code Playgroud)
这是在这里触发的:
<button (click)="destroy()">Destroy</button>
Run Code Online (Sandbox Code Playgroud)
调用这个"destroy"方法适用于我动态创建但不是静态创建的组件.
编辑: 所以看起来这部分删除了组件,但不是来自DOM,这与在动态创建的组件上调用"destroy"时发生的行为不同.此外,当我点击我试图销毁的组件时,我的点击事件功能仍会触发.
编辑2:我更新了我的ViewChild语法,以显式读取ComponentRef并返回"undefined":
@ViewChild(MyComponent, {read: ComponentRef}) myComponentRef: ComponentRef<MyComponent>;
Run Code Online (Sandbox Code Playgroud)
如果返回"未定义",那么我猜这可能是不可能的.
angular ×2