Angular2 access parent component's @input values

安稳与你 提交于 2019-12-23 17:33:35

问题


I'm trying to load a component dynamically using the ComponentResolver and ViewContainerRef services.

The child component loads ok and the template is rendered. However i want to access the inputs from the parent ('field' and 'values') inside the child component.

Any help would be much appreciated.

Parent component:

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) {
    }

}

Child component:

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) {
    }

}

回答1:


I think that you can leverage something like this:

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

See also the example https://plnkr.co/edit/bdGYvTf8y9LEw9DAMyN1?p=preview



来源:https://stackoverflow.com/questions/37368107/angular2-access-parent-components-input-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!