我可以为angular2中的一个组件添加两个模板吗

我可以为angular2中的一个组件添加两个模板吗

本文介绍了我可以为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-

我想要这样的东西

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

我想加载具有不同网址和视图的相同组件.

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中的一个组件添加两个模板吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 00:31