角度 + 引导(网格)+ 组件



我正在尝试使用 BootStrap 在 Angular 8 中开发一组表单组件,但有一个奇怪的行为。

以下 html 工作得很好:

<div class="form-group row">
<label for="input01" class="col-2 col-form-label">First Name</label>
<div class="col-4">
<input type="text" class="form-control" id="input01" placeholder="First Name">
</div>
<label for="input01" class="col-2 col-form-label">Last Name</label>
<div class="col-4">
<input type="text" class="form-control" id="input01" placeholder="Last Name">
</div>
</div>

我可以看到两个并排带有标签的输入(每个输入/标签 2+4 列(。

如果我拿这个狙击手并将其封装在一个组件中:

<label for="input01" class="col-2 col-form-label">First Name</label>
<div class="col-4">
<input type="text" class="form-control" id="input01" placeholder="First Name">
</div>

并按如下方式使用它:

<div class="form-group row">
<app-input-text></app-input-text>
<app-input-text></app-input-text>
</div>

它似乎缩小了。

请注意,它是相同的代码,但封装在一个组件中。

怎么了?

PS:这是StackBlitz运行代码:https://stackblitz.com/edit/angular-g3zxg3

提前谢谢。

您可以使用一些解决方法删除包装标签。一种是使用指令或属性选择器或使用模板注入,如下所示:

元件

export class InputTextComponent {
@ViewChild(TemplateRef, { static: false }) template;
constructor(private vcr: ViewContainerRef) {}
ngAfterViewInit() {
setTimeOut(()=> this.vcr.createEmbeddedView(this.template));
}
}

模板

<ng-template>
<label for="input01" class="col-2 col-form-label">First Name</label>
<div class="col-4">
<input type="text" class="form-control" id="input01" placeholder="First Name">
</div>
</ng-template>

斯塔克闪电战 和原始工作来源

编辑:正如@Emilio Numazaki在评论中所说,如果您公开可绑定属性,则会导致抛出提到的异常。因此,需要另一种解决方法来避免这种情况。

最新更新