我想要做的是有一个cshtml视图,其中包含角度组件,以及纯mvc的东西……
<side-bar></side-bar> <action-bar></action-bar> @{ Html.RenderPartial("_SuperLegacyPartialView"); }
我很难找到任何方法来做到这一点.这篇博客文章看起来很有前途 – http://www.centare.com/tutorial-angular2-mvc-6-asp-net-5/.它使用了一个模板指向由Mvc和AsyncRoute呈现的路径的templateUrl值,但是在Angular 2中它们都不再有效.这篇文章看起来很有前途 – http://gbataille.github.io/2016/02/16/Angular2-Webpack-AsyncRoute.html,但它使用了AsyncRoute也是,已被弃用.
这在Angular 1中非常容易.我们曾经手动将角度引导到Razor视图中,或者将局部视图渲染为组件/指令的templateUrl.在使用Webpack的最新Angular 2中执行此操作的最佳方法是什么?
解决方法
这个stackoverflow的答案–How can I use/create dynamic template to compile dynamic Component with Angular 2.0?在创建以下指令时非常有用.该指令将获取mvc局部视图的输出并进行编译.它允许发生Razor /服务器逻辑,并且还可以编译一些角度.虽然,实际上包含此MVC部分内的其他组件是有问题的.如果你这样做,请让我知道你做了什么.在我的情况下,我只需要服务器渲染,并将其放置在我的Angular 2水疗中心的确切位置.
MvcPartialDirective
import { Component,Directive,NgModule,Input,ViewContainerRef,Compiler,ComponentFactory,ModuleWithComponentFactories,ComponentRef,ReflectiveInjector,OnInit,OnDestroy } from '@angular/core'; import { RouterModule } from '@angular/router'; import { CommonModule } from '@angular/common'; import {Http} from "@angular/http"; import 'rxjs/add/operator/map'; export function createComponentFactory(compiler: Compiler,Metadata: Component): Promise<ComponentFactory<any>> { const cmpClass = class DynamicComponent {}; const decoratedCmp = Component(Metadata)(cmpClass); @NgModule({ imports: [CommonModule,RouterModule],declarations: [decoratedCmp] }) class DynamicHtmlModule { } return compiler.compileModuleAndAllComponentsAsync(DynamicHtmlModule) .then((moduleWithComponentFactory: ModuleWithComponentFactories<any>) => { return moduleWithComponentFactory.componentFactories.find(x => x.componentType === decoratedCmp); }); } @Directive({ selector: 'mvc-partial' }) export class MvcPartialDirective implements OnInit,OnDestroy { html: string = '<p></p>'; @Input() url: string; cmpRef: ComponentRef<any>; constructor(private vcRef: ViewContainerRef,private compiler: Compiler,private http: Http) { } ngOnInit() { this.http.get(this.url) .map(res => res.text()) .subscribe( (html) => { this.html = html; if (!html) return; if(this.cmpRef) { this.cmpRef.destroy(); } const compMetadata = new Component({ selector: 'dynamic-html',template: this.html,}); createComponentFactory(this.compiler,compMetadata) .then(factory => { const injector = ReflectiveInjector.fromResolvedProviders([],this.vcRef.parentInjector); this.cmpRef = this.vcRef.createComponent(factory,injector,[]); }); },err => console.log(err),() => console.log('MvcPartial complete') ); } ngOnDestroy() { if(this.cmpRef) { this.cmpRef.destroy(); } } }
在some-component.html中(假设您的mvc应用程序与您的spa共享域)
<mvc-partial [url]="'/stuffs/mvcstuff'"></mvc-partial>
MvcStuff.cshtml
@{ ViewBag.Title = "This is some MVC stuff!!!"; } <div> <h2>MVC Stuff:</h2> <h4>@ViewBag.Title</h4> <h2>Angular Stuff:</h2> <h4>{{1 + 1}}</h4> </div>
在StuffsController.cs中
public PartialViewResult MvcStuff() => PartialView();