【问题标题】:Rendering multiple view using a single component in angular使用单个组件以角度呈现多个视图
【发布时间】:2017-06-12 14:36:00
【问题描述】:

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

app.component.ts

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

@Component({
    selector: "mrdb-app",
    templateUrl: "./Scripts/app/app.component.html"

})


export class AppComponent {

    pageTitle: string = "Movies Review Database";

}

app.component.html

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

movie.component.ts

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

电影模块

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 { }

【问题讨论】:

  • 一个有两个模板的电影组件 - 一个组件不能有两个模板,但是你可以在一个组件模板内有多个 ng-template 标签,然后你可以使用@ViewChildren 然后使用 NgTemplateOutlet 指令渲染它们

标签: angular asp.net-mvc-5


【解决方案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>

只要您正确导入这些组件。

【讨论】:

  • @Tom 希望对您有所帮助!
【解决方案2】:
  1. 使用路由

movie.routing.ts

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-29
    • 1970-01-01
    • 2021-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-03
    相关资源
    最近更新 更多