我在一个页面上有三个组件,当我提交表单或调用特定函数后,如何重新加载该组件。假设您有 ckeditor 组件并放置文本、图像和视频,我想在提交后重新加载该组件,以便我可以编写新主题。
我在一个页面上有三个组件,当我提交表单或调用特定函数后,如何重新加载该组件。假设您有 ckeditor 组件并放置文本、图像和视频,我想在提交后重新加载该组件,以便我可以编写新主题。
something.val('')
并不傻,因为重新加载组件首先意味着重新加载所有依赖项,例如远程配置等。我觉得傻的是当唯一变化的是某个输入框的值时就重新加载整个组件。@Directive({
selector: '[showOrReloadOn]'
})
export class ShowOrReloadOnDirective implements OnChanges {
@Input('showOrReloadOn')
private reload: BehaviorSubject<boolean>;
private subscription: Subscription;
constructor(
private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef,
) { }
ngOnInit() {
this.subscription = this.reload.subscribe(show => {
this.viewContainer.clear();
if (show) {
this.viewContainer.createEmbeddedView(this.templateRef);
}
});
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
@Component({
selector: 'my-reloaded-component',
template: `component that is loaded {{loadedCount}} times`,
})
export class ReloadedComponent {
static loadedCount = 0;
constructor() {
// here we increase the static counter
// which is component-instance-independent
// meanwhile constructor is triggered only once
// that's why we are sure the component gets rerendered
this.loadedCount = ++ReloadedComponent.loadedCount;
}
}
@Component({
selector: 'my-app',
template: `
<div>
<button (click)="reload(true)">Show / Reload</button>
<button (click)="reload(false)">Hide</button>
</div>
<my-reloaded-component *showOrReloadOn="reloader"></my-reloaded-component>
`,
})
export class App {
// this is our communication point
// here we push true to show and false to hide the element
// just to cover *ngIf functionality by the way to avoid problems
// we also pass true as initial value in order to show the component directly
reloader = new BehaviorSubject<boolean>(true);
reload(show: boolean) {
// trigger reload if true or hiding if false
this.reloader.next(show);
}
}
something.val('')
而不是重新加载组件是愚蠢的。通过重新加载组件,您可以避免 JavaScript 冲突或意外发生的情况。 - Yazan Mehrez