gpt4 book ai didi

javascript - Angular2 访问父组件的@input 值

转载 作者:太空狗 更新时间:2023-10-29 18:21:31 24 4
gpt4 key购买 nike

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

关于javascript - Angular2 访问父组件的@input 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37368107/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com