我是编程新手,也是Angular新手,所以我想我需要一些帮助。我目前正在浏览Angular文档以寻找答案,但有时这里的解释要好得多!
根据我之前关于为Angular Material提供的MatDialog创建包装器服务的问题,我想知道是否可以将组件类型的名称字符串转换为我们传递给MatDialog.open方法的组件或模板引用(ComponentType | TemplateRef)?说不通吗?我会解释得更清楚一点...
这里我有一个用于MatDialog的包装器服务,请注意,我们必须将"componentRef“传递给dialog.open方法
import {Injectable} from '@angular/core';
import {MatDialog} from '@angular/material';
@Injectable({
providedIn: 'root'
})
export class MatDialogWrapperService {
constructor(private dialog: MatDialog) {
}
open(componentRef, config = {}) {
this.dialog.open(componentRef, config);
}
}现在我可以在组件中使用包装器服务并传递componentRef ...
import { ModalFormComponent } from './forms/modal-form.component';
@Component({
selector: 'app-intro-form',
templateUrl: './intro-form.component.html',
providers: [MatDialogWrapperService],
styleUrls: ['./intro-form.component.scss']
})
constructor(private modalService: MatDialogWrapperService ) {
}
modalCall() {
this.modalService.open(ModalFormComponent, {
width: '500px'
});
}假设我希望在Modal中呈现的组件是动态的,或者传递到我的组件中?在上面的示例中,它是用我使用import语句传递给组件的值ModalFormComponent“硬编码”的。我是否可以假设将该值作为@Import()传递,并将字符串值转换为类型引用?例如,在我的HTML中,如下所示
<app-intro-form [modalComponent]="'ModalFormComponent'"></app-intro-form>在我的组件中
@Component({
selector: 'app-intro-form',
templateUrl: './intro-form.component.html',
providers: [MatDialogWrapperService],
styleUrls: ['./intro-form.component.scss']
})
@Input() componentRef: any; // this needs to be wrapped or converted
constructor(private modalService: MatDialogWrapperService ) {}
modalCall() {
this.modalService.open(componentRef, {
width: '500px'
});
}@Input()需要从字符串转换为引用才能工作,但我不确定如何处理。我目前正在尝试自学Angular,所以我意识到有时我的问题可能没有实际意义,但这不是一个生产应用程序……这样我就可以学习如何编写代码,并且可以很好地编写代码!
在此之前,非常感谢您。
发布于 2019-02-27 23:00:12
最简单的方法可能是使用某种类型的注册表来跟踪您的不同组件。
@Injectable({
providedIn: 'root'
})
export class ComponentRegistryService{
public getComponentByName(name: string) {
switch (name) {
case "ConfirmComponent":
return ConfirmComponent;
...
}
}
}然后你可以在你的包装器中使用它:
constructor(private modalService: MatDialogWrapperService, private registry: ComponentRegistryService) {}
modalCall() {
this.modalService.open(registry.getComponentByName(componentRef), {
width: '500px'
});
}https://stackoverflow.com/questions/54907577
复制相似问题