我得到了这个组件的层次结构。拥有2个子组件的父组件。我希望第一个子组件更新父组件的属性,然后第二个子组件重新呈现。我得到了带有两个子组件的主组件:一个带有select html输入,第二个是数据表,数据来自主组件作为输入。其想法是,当我更改所选值时,我希望更改主组件中的数据,以便数据表可以从主组件中获得新数据。我该怎么做呢?
在第一个孩子中:
@Output() optionSelected = new EventEmitter<string>();@Input()数据;
在父级中:
@Input() displayOption: string;
@Output() dataToSelect 当displayOption更新时,我希望第二个子对象重新呈现
发布于 2019-02-28 19:20:42
如果你使用的是ChangeDetectionStaretgy.OnPush,在你的子组件中传递可观察到的数据可能会很有用,并使用异步管道。这样,子组件将仅在observable发出时重新绘制:
第一个孩子:
@Output() optionSelected = new EventEmitter<string>();
selectOption() {
this.optionSelected.emit('firstChild')
}First Child html:
<button (click)="selectOption()">Select<button>第二个孩子:
@Input() data$;第二个Child.html:
<p>{{data$ | async}}</p>父级:
data = new BehaviorSubject('')
setSelectedOption(val) {
this.data.next(val)
}Parent.html:
<first-child (optionSelected)="setSelectedOption($event)"></first-child>
<second-child [data$]=""></second-child>发布于 2019-02-28 19:00:27
@Output装饰器用于在子组件与父组件之间共享数据。EventEmitter用于发送值。
child.component.ts
@Output() optionSelected = new EventEmitter<string>();
sendDataToChild() {
this.optionSelected.emit('hello');
}parent.component.html
在子组件的选择器中,您可以使用(optionSelected)侦听事件,当事件被发出时,父组件中的log()方法将被调用。
<child-comp (optionSelected)="log($event)"></child-comp>parent.component.ts
log(value) {
console.log(value);
}发布于 2019-02-28 22:58:47
要动态重新呈现组件,可以使用ComponentFactoryResolver,如下所示:
在您的HTML模板中,您需要一个新组件的“锚”:
<ng-template #child2></ng-template>在您的parent-component.ts中,您将需要通过ViewChild引用锚点,并且您将需要注入ComponentFactoryResolver:
constructor(private cfr: ComponentFactoryResolver) { }
@ViewChild('child2', { read: ViewContainerRef }) childHost: ViewContainerRef;
renderChild2(data ?: any) { // im making this optional because i dont know if you require any data to init the component
this.childHost.clear(); // clear the current rendered component inside the anchor (if any)
const factory = this.cfr.resolveComponentFactory(<YOUR COMPONENT NAME>);
const componentReference = this.childHost.createComponent(factory);
if (data) {
componentReference.instance.data = data; // you can access any public property/method in your component via instance
}
}只要想要重新呈现child2组件,就需要调用renderChild2() fcn。
https://stackoverflow.com/questions/54923904
复制相似问题