我可以在angular2中为一个组件添加两个模板吗? [英] Can I add two template for one component in angular2?

查看:50
本文介绍了我可以在angular2中为一个组件添加两个模板吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只有一个组件,其中包含一个html和.ts文件.由于某些原因,我必须创建多个页面(HTML)页面.
是否可以为单个类(组件)创建多个(html)页面?
还是可以向组件提供动态TemplateUrl?

I have one component with one html and .ts file. For some reasons I have to create multiple pages (HTML) pages.
Is it possible to create multiple (html) pages for single class (component)?
Or is it possible to provide dynamic TemplateUrl to the component?

我的主要动机是提供不同的URL和使用不同的视图(HTML页面),但使用单个类(.ts类即组件)?
我已经看到以下提到的许多与此相关的问题,但无法找到确切的解决方案-

My main motive is to provide different URL and to use different view (HTML pages) but using single class (.ts class i.e component)?
I have seen many questions referred below related to that but unable to found exact solution-

  • Dynamic template URLs in Angular 2
  • How can I have dynamic templateUrl for Angular2 Component?

我想要这样的东西

{ path: '/Login', component: LogIn, name: "Login"},
{ path: '/Login2', component: LogIn, name: "Login" },
{ path: '/Login3', component: LogIn, name: "Login" }

我想用不同的URL和视图加载相同的组件.

I want to load same component with different url and view.

推荐答案

通过继承可以做到这一点.不同的视图和样式模板,但(基本)相同的基础组件代码.您仍然必须声明@Component元数据,因此,如果您使用值访问器等,则也需要重新定义它们.

This is possible with inheritance. Different view and style templates, but (basically) the same underlying component code. You still have to declare the @Component metadata, so if you're using value accessors etc, you will need to redefine those too.

第一个组件:

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

import { KeyValuePairBase } from '../../model/key-value-pair-base'

@Component({
  moduleId: module.id,
  selector: 'select-list',
  templateUrl: './select-list.component.html',
  styleUrls: ['./select-list.component.scss']
})
export class SelectListComponent implements OnInit {
  @Input() private data: KeyValuePairBase[];

  constructor() {
    super();
  }

  ngOnInit() {
    if (!this.name) throw new Error("'name' property is required by 'select-list' component");
    if (!this.friendlyName) throw new Error(`'friendlyName' property is required by 'select-list' component '${this.name}'`);
  }
}

第二部分:

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

import { SelectListComponent } from '../select-list/select-list.component'

@Component({
  moduleId: module.id,
  selector: 'radio-list',
  templateUrl: './radio-list.component.html',
  styleUrls: ['./radio-list.component.scss']
})
export class RadioListComponent extends SelectListComponent {
}

这篇关于我可以在angular2中为一个组件添加两个模板吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆