2016-09-12 13 views
1

ASP.NET MVCでAngular 2を使用しようとしていますが、コンポーネントへのビューへの適切なマッピング方法が見つかりません。たとえば、IndexアクションとIndex.cshtmlビューを持つHomeControllerがあるとします。ビューの内側に、<home></home>要素を追加して、Angular 2コンポーネントのセレクタにマップします。Angular 2コンポーネントをASP.NET MVCビューに接続するにはどうすればよいですか?

import { Component } from '@angular/core'; 

@Component({ 
    selector: 'home', 
    template: '<h1>Home component</h1>' 
}) 
export class HomeComponent { 
} 

私のAppModuleのbootstrapプロパティにコンポーネントを追加しない限り、コンポーネントはトリガーされません。これにより、私のアプリはbootstrapプロパティの中にいくつかのコンポーネントを持つことになります。

import { NgModule } from '@angular/core'; 
import { BrowserModule } from '@angular/platform-browser'; 

import { AppComponent } from './app.component'; 
import { HomeComponent } from './home.component'; 

@NgModule({ 
    imports: [BrowserModule], 
    declarations: [AppComponent, HomeComponent], 
    bootstrap: [AppComponent, HomeComponent] 
}) 
export class AppModule { 
} 

これは正しい方法ですか?

部分ビュー内に別のコンポーネントの要素セレクタがある場合は、最初の部分ビューのコンポーネントだけが呼び出されます。パーシャルビューをレンダリングするたびにコンポーネントを呼び出す方法を教えてください。私の部分的なビューが同じページに複数回レンダリングされたとしても?

答えて

1

正しいビューを見つけてレンダリングするテンプレートコントローラを追加できます。

あなたAngular2コンポーネントで

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Threading.Tasks; 
using Microsoft.AspNet.Mvc; 

// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860 

namespace DemoApp.Controllers 
{ 
    [Route("template")] 
    public class TemplateController : Controller 
    { 
     [Route("{component}/{view}")] 
     public IActionResult Get(string component, string view) 
     { 
      string path = string.Format("~/Views/{0}/{1}.cshtml", component, view); 

      return PartialView(viewName: path); 
     } 

     [Route("{area}/{component}/{view}")] 
     public IActionResult Get(string area, string component, string view) 
     { 
      string path = string.Format("~/Views/{0}/{1}/{2}.cshtml", area, component, view); 

      return PartialView(viewName: path); 
     } 
    } 
} 

サンプル、テンプレートコントローラを、見てみましょう、あなたは次のようなテンプレートを使用することができ、

import { Component, Inject, OnInit } from '@angular/core'; 
import { REACTIVE_FORM_DIRECTIVES } from '@angular/forms'; 

@Component({ 
    selector: 'overview', 
    templateUrl: 'template/overview/index' 
}) 
export class OverviewComponent { 
} 

私はあなたを助け願っています。

+0

これは角度2で動作しなくなりました。 –

関連する問題