【问题标题】:Angular + Bootstrap (grid) + ComponentAngular + Bootstrap(网格)+ 组件
【发布时间】:2020-04-17 16:44:42
【问题描述】:

我正在尝试使用 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

提前致谢。

【问题讨论】:

  • Bootstrap 需要 .col 成为 .row 的直接子级。但事实并非如此,因为中间有 app-input-text。
  • 是的,你是对的,但是如果我坚持这条规则,我该如何创建多列和单列输入表单?我的意思是,如果我需要创建一个单行字段 (12),我会将 app-input-text 包装在一行中,如果我需要两个输入,我可以做我在示例中所做的事情等等。 .
  • 使用 .row inside 组件模板,有两个子 .col-4 和 .col-8。在父级中使用带有两个 children.col-6 的 .row。
  • 它可以工作,但我会失去灵活性,因为我的目的是允许组件用户设置标签和输入的宽度。
  • 你为什么不能这样做?实际上,您将获得灵活性,因为您的组件可以在任何地方使用,而不仅仅是像您所拥有的那样在 .row 中使用。

标签: angular bootstrap-4


【解决方案1】:

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

组件

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>

Stackblitz 以及work around的原始来源

编辑:正如@Emilio Numazaki 在 cmets 中所述,如果您公开可绑定属性,则会引发上述异常。因此,需要另一种解决方法来避免这种情况。

【讨论】:

  • 是的!这正是我需要的!谢谢!
  • Heldar,为了避免 ExpressionChangedAfterItHasBeenCheckedError 错误,我只做了一项更改:我没有直接调用 this.vcr.createEmbeddedView(this.template),而是做了:Promise.resolve(null).then (() => this.vcr.createEmbeddedView(this.template));
  • 向组件添加更多参数时避免错误很重要。请查看有错误的版本:stackblitz.com/edit/angular-y2wnde
猜你喜欢
  • 2019-03-31
  • 2018-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多