gpt4 book ai didi

angular - 动态组件 - createComponent - OnChanges

转载 作者:行者123 更新时间:2023-12-04 16:01:02 29 4
gpt4 key购买 nike

我正在通过 createComponent 创建一个动态组件方法,但我在获取 child 时遇到问题组件更新它的 inputparent 传入的值来自 component.instance.prop = somevalue方法,但是当我更新 parent 中的值时 child 没有更新它的引用。

父组件:

import {
Component,
ViewChild,
ViewContainerRef,
ComponentFactoryResolver,
AfterContentInit
} from '@angular/core';

import { ChildComponent } from '../child/child.component';

@Component({
selector: 'parent-component',
template: `
<div>
<input type="text" (keyup)="name = $event.target.value">
<span>{{ name }}</span>
</div>
<ng-container #container></ng-container>
`,
styles: []
})
export class ParentComponent implements AfterContentInit {
@ViewChild('container', { read: ViewContainerRef}) container: ViewContainerRef;
private _name = 'John Doe';
get name() {
return this._name;
}
set name(name: string) {
this._name = name;
}
constructor(private resolver: ComponentFactoryResolver) { }

ngAfterContentInit() {
let factory = this.resolver.resolveComponentFactory(ChildComponent);
let component = this.container.createComponent(factory);
component.instance.name = this.name;
}
}

子组件:
import {
Component,
OnInit,
Input,
OnChanges,
SimpleChanges
} from '@angular/core';

@Component({
selector: 'child-component',
template: `
<div>
{{ name }}
</div>
`,
styles: []
})
export class ChildComponent implements OnChanges {
_name: string;
get name() {
return this._name;
}
set name(name: string) {
this._name = name;
}
constructor() { }
ngOnChanges(changes: SimpleChanges) {
console.log('onchanges ', changes);
this._name = changes.name.currentValue;
}
}

问题:如何获得动态 child通过 createComponent() 创建的组件当 parent 中的值发生变化时更新其值的方法成分?

最佳答案

您可以在父组件中执行此操作。 Here stackblitz 中的例子。

template: `
<div>
<input type="text" (keyup)="onKeyUp($event)">
<span>{{ name }}</span>
</div>
<ng-container #container></ng-container>
`,

childComponent: ChildComponent;

ngAfterContentInit() {
let factory = this.resolver.resolveComponentFactory(ChildComponent);
let component = this.container.createComponent(factory);
this.childComponent = component.instance;
this.childComponent.name = this.name;
}

onKeyUp($event) {
const changes = {
name: new SimpleChange(this.name, $event.target.value, false)
}

this.name = $event.target.value;
this.childComponent.ngOnChanges(changes);
}

关于angular - 动态组件 - createComponent - OnChanges,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50500385/

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