Angular2访问父组件的@input值

时间:2016-05-21 21:17:29

标签: javascript typescript angular angular2-components

我尝试使用ComponentResolver和ViewContainerRef服务动态加载组件。

子组件加载正常并且呈现模板。但是,我想访问子组件内的父项('字段'和'值')的输入。

非常感谢任何帮助。

父组件:

RewriteEngine on

# skip all files and directories from rewrite rules below
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]

RewriteRule ^(api.*)$ /api.php/$1 [L]
RewriteRule ^(admin.*)$ /admin.php/$1 [L]

RewriteCond $1 !^(index\.php|admin\.php|api\.php|admin|api|_|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]

子组件:

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

}

1 个答案:

答案 0 :(得分: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