Angular2 访问父组件的@input值



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

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

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

相关内容

  • 没有找到相关文章

最新更新