我正在尝试使用 ComponentResolver 和 ViewContainerRef 服务动态加载组件。
子组件加载正常并呈现模板。但是我想访问子组件内的父级(“字段”和“值”)的输入。
任何帮助将非常感激。
父组件:
import {Component, Input, ViewChild, ComponentFactory, ViewContainerRef, ComponentResolver} from '@angular/core';
import {MyInputComponent} from './my-input.component';
@Component({
selector: 'my-field',
template: `
<label class="control-label">
<span>{{field.label}}</span>
<span class="required">*</span>
</label>
<div #target></div>
`
})
export class MyFieldComponent {
@Input() field;
@Input() values;
@ViewChild('target', { read: ViewContainerRef }) target;
ngAfterViewInit() {
this.compiler.resolveComponent(MyInputComponent).then((factory: ComponentFactory<any>) => {
this.target.createComponent(factory);
});
}
constructor(public viewContainerRef: ViewContainerRef, private compiler: ComponentResolver) {
}
}
子组件:
import {Component, Input, ViewContainerRef} from '@angular/core';
@Component({
selector: 'my-input',
template: `
This is an input component!!!
`
})
export class MyInputComponent {
@Input() field: any;
@Input() values: any;
ngOnInit() {
console.log(this);
}
constructor(public viewContainerRef: ViewContainerRef) {
}
}