angular8 - 自定义 Angular 2+ 步进模块
问题描述
一开始我想说我知道有准备好使用 CDK 或 Materials 的步进器,但我想创建“我自己的”以学习 Angular 8。
老实说,我不知道现在应该在哪里寻求帮助,这就是我决定在这里写的原因。也许有人给我一些建议,我会在最后发表我的作品。
让我们开始吧:索引 HTML 代码如下所示:
<stepper>
<step>
<ng-template step-label>First name</ng-template>
<input placeholder="First name" required>
<div>
<button >Next</button>
</div>
</step>
<step>
<ng-template step-label>Last name</ng-template>
<input placeholder="Last name" required>
<div>
<button >Next</button>
</div>
</step>
<step>
<ng-template step-label>Address name</ng-template>
<input placeholder="Address" required>
<div>
<button >Next</button>
</div>
</step>
</stepper>
组件+指令
@Directive({selector: '[step-label]'})
export class StepLabel{
constructor(public template: TemplateRef<any>){};
}
@Component({selector: 'step-header', templateUrl: 'step-header.html'})
export class StepHeader{
@Input() label: TemplateRef<StepLabel>;
}
@Component({
selector: 'step',
template: '<ng-template><ng-content></ng-content></ng-template>'
})
export class Step{
@ViewChild(TemplateRef, {static: true}) content: TemplateRef<Step>;
@ContentChild(StepLabel, {static: true}) label: TemplateRef<StepLabel>;
}
@Component({selector: 'stepper', templateUrl: './stepper.html'})
export class Stepper implements AfterContentInit {
stepsArray = [];
@ContentChildren(Step) steps: QueryList<Step>;
ngAfterContentInit() {
this.stepsArray = this.steps.toArray();
}
}
步进器.html
<div class="header-steps" style="bordeR: 1px solid green; padding: 10px;">
<ng-container *ngFor="let step of stepsArray; let i = index; let isLast = last">
<step-header [label]="step.label"></step-header>
</ng-container>
</div>
<div style="border: 1px solid blue; padding: 5px; margin: 5px;" class="content-steps">
<div *ngFor="let step of stepsArray; let i = index">
<ng-container *ngIf="step" [ngTemplateOutlet]="step.content"></ng-container>
</div>
</div>
步骤=header.html
<div class="step-label">
<ng-container *ngIf="label" [ngTemplateOutlet]="label.template"></ng-container>
</div>
我已经更新了整个“基本”项目。有用。我有一个问题。为什么在指令 StepLabel 中必须是构造函数。我试图添加一些这样的想法:
@ViewChild(TemplateRef, {static: true}) template: TemplateRef<StepLabel>;
但它不起作用。
解决方案
在您的步骤组件的模板中,将 ng-content 包装在 ng-template 中
template: '<ng-template><ng-content></ng-content></ng-template>'
然后使用获取模板ViewChild
@ViewChild(TemplateRef, { static: true }) content: TemplateRef<any>;
最后你会得到类似的东西:
@Component({
selector: 'step',
template: '<ng-template><ng-content></ng-content></ng-template>'
})
export class Step {
@ViewChild(TemplateRef, { static: true }) content: TemplateRef<any>;
}
推荐阅读
- javascript - 当滚动在移动/笔记本电脑中不起作用时加载更多项目
- reactjs - 如何使 Expo Camera View 可点击
- javascript - 设置没有 css 剪辑路径的 iframe 包装器 div
- ruby-on-rails - 如何将 HTTParty 响应保存到 db?(更新!)
- go - 通道并发问题
- ios - 是否有任何文档可用于将 google CAF 集成到自定义 iOS 框架中?
- php - 删除文件夹期间 Laravel 存储“权限被拒绝”
- python - 使用序列化程序在restframework中进行API调用的Django一对多关系
- vba - 如果此字段为空,如何更改连续子表单字段的背景色
- powershell - 从powershell中运行更改目录的批处理文件什么都不做