3

我正在尝试使用 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) {
    }

}
4

1 回答 1

4

我认为你可以利用这样的东西:

this.compiler.resolveComponent(MyInputComponent).then((factory: ComponentFactory<any>) => {
   let component = this.target.createComponent(factory);
   component.instance.field = this.field;
});

另请参阅示例https://plnkr.co/edit/bdGYvTf8y9LEw9DAMyN1?p=preview

于 2016-05-22T04:53:43.303 回答