有没有办法在动态创建的组件中访问@Input变量?

Cro*_*asr 2 angular

我正在向表单中动态添加行,并希望每个新行都具有唯一的ID号。

我有以下代码来添加新组件(代表新行),但是我发现它component.instance仅包含新创建的组件的“常规”属性,而不包含用修饰的属性@Input()。有没有办法动态写入/修改@Input()属性?当动态创建一个组件时,自然会假设必须有一种直接的方式以某种方式提供@Input()值!

const componentFactory = this.componentFactoryResolver.resolveComponentFactory(thisType);
const component = this.subEnrollForm.container.createComponent(componentFactory);
component.instance.rowData.push(newRow); //rowData is a property in the
                                       dynamically-created component and 
                                       is decorated with @Input()
Run Code Online (Sandbox Code Playgroud)

这是动态创建的组件:

export class SubEnrollFormRowComponent implements OnInit, DoCheck, OnChanges, AfterContentInit, AfterViewInit {
 @Input() rowData; 
  objKeys: Array<any> = [];
  subKeys: Array<any> = [];
Run Code Online (Sandbox Code Playgroud)

我看到一个具有以下答案的旧帖子,但希望随后添加了新功能来解决此问题:

不能,Angular2绑定仅适用于静态添加到组件模板的组件和指令。

对于所有其他情况,请使用共享服务,如 https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service中所述

您也可以使用

让componentRef = entryPoint.createComponent(componentFactory); componentRef.instance.someProp ='someValue'; componentRef.instance.someObservableOrEventEmitter.subscribe(data => this.prop = data);

后一种解决方案对我不起作用,也没有建议将组件转换为type <any>。我对上述services方法的解释是,我需要为孙子创建一个Observable,以监视祖父母何时尝试更新孙子的@Input()属性,但是在我看来,这种方法对很多不必要的编码和开销来实现应该非常简单明了的东西(除非我缺少某些东西,这很有可能!)。如果有人可以通过相对简单的方法来初始化/动态修改以@Input装饰的孙子组件属性,请在此先感谢!

cri*_*n.t 5

用装饰的属性@Input仍然是类属性,并且可以像其他任何属性一样访问。

我创建了一个工作示例:https : //stackblitz.com/edit/angular-6-template-yih3sx?file=src%2Fapp%2Fapp.component.ts