使用角度中的单个组件渲染多个视图

时间:2017-06-12 06:22:56

标签: angular asp.net-mvc-5

我正在构建一个与MVC 5集成的Angular 4应用程序。我正在创建一个包含两个模板的Movie组件。一个列出电影,另一个是添加电影。如何使用Movie组件处理任一模板的渲染。目前,templateURL仅包含一个模板。代码如下

app.component.ts

<div>
    <h1>{{pageTitle}}</h1>
    <app-movie></app-movie>  //This selector belongs to movie component
</div>

app.component.html

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

@Component({
    selector: 'app-movie',
    templateUrl: './Scripts/movie/movie-list.component.html'

})
export class MovieComponent implements OnInit {

    pageTitle: string = "Movie List";

    constructor() { }

    ngOnInit() {
    }

}

Movie-list.component.html
//Assume I have written a logic to display list of movies

Movie-Add.component.html
//Assume I have written a html for data entry screen

movie.component.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MovieComponent } from './movie.component';

@NgModule({
    imports: [
        CommonModule
    ],
    declarations: [MovieComponent],
    exports: [MovieComponent]
})
export class MovieModule { }

电影模块

if (ContextCompat.checkSelfPermission(getActivity(),
                    Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(getActivity(),
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                //Permission not Granted...
                requestPermissions(
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
                        Constant.RequestPermissions.LOCATIONS);

            } else {

                //Permission has been already Granted...

            }

2 个答案:

答案 0 :(得分:1)

您好有两种方法可以实现这一目标。 您可以使用路由,也可以使用自定义标记。如果您正在使用路由,则需要创建app.routing.ts文件并在其上定义所有路径和组件。喜欢这个

app.routing.ts

import { Routes, RouterModule } from "@angular/router";
import { ModuleWithProviders }  from '@angular/core';

import { AddMovieComponent } from './addmovie/addmovie.component';
import { ListMovieComponent } from './listmovie/listmovie.component'; 

const APP_ROUTES: Routes = [

  { path: 'addmovie', component: AddMovieComponent },
  { path: 'listmovie', component: ListMovieComponent }

];

export const routing = RouterModule.forRoot(APP_ROUTES);

另一种方法是在app.component.html中编写这些标记

<addmovie></addmovie>
<listmovie></listmovie>

如果您正确导入了这些组件。

答案 1 :(得分:0)

  1. 使用路由
  2. <强> movie.routing.ts

    export const routes: Routes = [
      {
        path: '',
        component: MovieComponent
      }, {
        path: 'new',
        component: AddMovieComponent
      }, {
        path: 'edit/:id',
        component: EditMovieComponent
      }
    ];
    
    1. 尝试* ngIf