我有一个从组件动态创建的模态,这样:
@Injectable()
export class SharedService {
showModal:Subject<any> = new Subject();
}
@Component({
selector: 'comp-comp',
template: `MyComponent dataToPass: {{dataToPass}}, dataToPass2: {{dataToPass2}}
<button (click)="doSomethingAndClose()">Do something and close</button>`
})
export class CompComponent {
private dataToPass2;
constructor() {}
ngAfterContentInit() {
this.dataToPass2 = this.dataToPass + ' hello';
}
doSomethingAndClose() {
this.dataToPass2 = this.dataToPass + ' I'm gonna close;
console.log(this.dataToPass2);
this.destroy();
}
}
export class ModalComponent {
@ViewChild('theBody', {read: ViewContainerRef}) theBody;
theHeader: string = '';
dataToPass: string = '';
cmpRefBody:ComponentRef<any>;
constructor(
sharedService:SharedService,
private componentFactoryResolver: ComponentFactoryResolver,
injector: Injector) {
sharedService.showModal.subscribe(data => {
if(this.cmpRef) {
this.cmpRef.destroy();
}
let factory = this.componentFactoryResolver.resolveComponentFactory(data.type);
this.cmpRef = this.theBody.createComponent(factory);
this.cmpRef.instance.dataToPass = data.dataToPass;
this.dataToPass = data.dataToPass;
this.theHeader = data.title;
console.log(data.title);
console.log(data.dataToPass);
$('#theModal').modal('show');
});
}
close() {
if(this.cmpRef) {
this.cmpRef.destroy();
}
this.cmpRef = null;
}
}
@Component({
selector: 'my-app',
template: `
<div>
<h2>Hello</h2>
<button (click)="showDialog()">show modal</button>
<child-component></child-component>
</div>
`,
})
export class App {
constructor(private sharedService:SharedService) {}
showDialog() {
this.sharedService.showModal.next({'type': CompComponent, 'title': 'titolo1', 'dataToPass': 'dataToPass'});
}
}
(推荐人:Angular 2 modals shared between components)。
在模态组件内部有一个close()
函数,this.CmpRef.destroy()
关闭模态本身。
正如你在我的插件中看到here一样,我想让模态组件从模态中动态加载的组件中关闭。
我尝试使用函数doSomethingAndClose()
来完成它,但它给了我这个错误:
VM1882 core.umd.js:3472 EXCEPTION: Cannot set property stack of [object Object] which has only a getter
我不知道怎么做,因为在动态创建的组件内部我没有对模态父组件的任何引用...