Muh*_*ras 5 angular angular-dynamic-components
我正在 Angular 8 中工作,我有一个组件,我有大约 6 个或更多模板。用户将从界面或某种逻辑中选择使用哪一个,比方说,
if(a==2) use template 'ddd.html'
else user template 'sss.html'
Run Code Online (Sandbox Code Playgroud)
我不想在这里使用它
@Component({
selector: 'app-maindisplay',
templateUrl: './maindisplay.component.html',
styleUrls: ['./maindisplay.component.css']
})
Run Code Online (Sandbox Code Playgroud)
我希望它出现在任何函数中,无论是构造函数还是任何其他函数。如果它使用任何子组件或指令类型的逻辑来解决就可以了,我唯一需要的是在该逻辑上选择模板。我通常会将相同的数据传递给所有模板,只有它们的设计会改变。
我遇到了同样的问题,并且正在寻找与您要求的相同的解决方案,但我没有找到任何解决方案。我通过继承解决了这个问题。您必须创建一个没有任何模板的组件,该组件将作为父类。该组件将包含您需要的所有逻辑。我只插入一个输入只是为了展示它是如何工作的:
基础组件.ts
@Component({
selector: 'base',
template: ''
})
export class BaseComponent{
@Input()
text: string;
}
Run Code Online (Sandbox Code Playgroud)
然后你必须创建不同的模板作为扩展 BaseComponent 的不同组件:
模板1.组件.ts
@Component({
selector: 'template1',
template: '<button>{{text}}</button>'
})
export class Template1Component extends BaseComponent{}
Run Code Online (Sandbox Code Playgroud)
模板2.组件.ts
@Component({
selector: 'template2',
template: '<input [value]="text">'
})
export class Template2Component extends BaseComponent{}
Run Code Online (Sandbox Code Playgroud)
现在你可以像这样简单地使用它们:
应用程序组件.html
<button (click)="template = (template == 1) ? 2 : 1">Change template</button>
<br><br>
<ng-container [ngSwitch]="template">
<template1 text="Template1 input text" *ngSwitchCase="1"></template1>
<template2 text="Template2" *ngSwitchCase="2"></template2>
</ng-container>
Run Code Online (Sandbox Code Playgroud)
应用程序组件.ts
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
template = 1;
}
Run Code Online (Sandbox Code Playgroud)
看看这里的工作示例
希望这能有所帮助。
| 归档时间: |
|
| 查看次数: |
2134 次 |
| 最近记录: |