Angular2 访问父组件的@input 值
Angular2 access parent component's @input values
我正在尝试使用 ComponentResolver 和 ViewContainerRef 服务动态加载组件。
子组件加载正常,模板已呈现。但是我想访问子组件内父级('field' 和 'values')的输入。
如有任何帮助,我们将不胜感激。
父组件:
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;
});
我正在尝试使用 ComponentResolver 和 ViewContainerRef 服务动态加载组件。
子组件加载正常,模板已呈现。但是我想访问子组件内父级('field' 和 'values')的输入。
如有任何帮助,我们将不胜感激。
父组件:
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;
});