【发布时间】:2021-04-21 14:21:02
【问题描述】:
我有一个带有 ng-content 的模态组件。在这个 ng-content 中,我可以通过注入器传递其他组件。无论如何,我需要在其中传递一个对象来编辑数据。但我需要一些帮助。这是模态组件html:
<div class="modal">
<div class="modal-body">
this is my Object: {{model | json}}
<ng-content></ng-content>
</div>
<div class="modal-footer">
<button (click)="sendMessage()">success</button>
<button>abort</button>
</div>
</div>
ng-content 中的组件可能会有所不同。在我的示例中,我有一个输入。我需要在该组件中传递一个模型。
我使用带有注入器的服务将内容传递到我的 modalComponent,并在函数“open”中定义了一个参数 obj,它是我需要在 ng-content 组件中查看的对象。 (参数存储在我的模态组件的“模型”输入中)。
@Injectable()
export class ModalService {
dialogComponentRef: ComponentRef<ModalComponent>;
private subject = new Subject<any>();
open(content: any, obj: any) {
const contentComponentFactory = this.cfResolver.resolveComponentFactory(content);
const modalComponentFactory = this.cfResolver.resolveComponentFactory(ModalComponent);
const contentComponent = contentComponentFactory.create(this.injector);
const modalComponent = modalComponentFactory.create(this.injector, [[contentComponent.location.nativeElement]]);
modalComponent.instance.model = obj;
this.dialogComponentRef = modalComponent;
document.body.appendChild(modalComponent.location.nativeElement);
this.appRef.attachView(contentComponent.hostView);
this.appRef.attachView(modalComponent.hostView);
}
}
这是我的 modalComponent 类:
export class ModalComponent {
@Input() model: any;
sendMessage() {
this.modalService.sendMessage();
}
constructor(private modalService: ModalService) {}
}
因此我用这个html定义了一个组件:
<input type="text" value="name" placeholder="name">
在此输入中,我希望看到用于编辑此值的对象。
我找不到将对象包含在内容组件中的解决方案....我需要它,因为我有一个必须编辑一些值的表单。
这是我的 stackblitz 示例:Example
【问题讨论】:
-
所以你要传递表单组件和一些预填充的值(表单中要传递的数据?)
-
是的。一个组件,它有一个表单,并最终在表单中传递一个对象。
标签: javascript angular typescript