【问题标题】:Angular *ngFor "id" tag generation incorrect with `mat-button-toggle`Angular *ngFor“id”标签生成不正确与`mat-button-toggle`
【发布时间】:2020-01-08 03:08:45
【问题描述】:

我正在尝试从数组中生成按钮列表:

<div class="card-container">
    <mat-button-toggle *ngFor="let button of buttonsFromApi" id={{button.id}} class="problemButton" [disabled]="sso.invalid" >{{button.id}}</mat-button-toggle>
</div>

buttonsFromApi 包含 5 个对象,例如:

{
    displayName: "Button name", 
    id: "100",
}

所以基本上我希望按钮显示displayName(这可行)并具有对象中的ID。后者不会发生,而是按钮具有像100-button200-button 这样的ID,而不是100200。为什么会这样,我怎样才能使它成为100200而不是100-button200-button

【问题讨论】:

  • 也许它 id 属性的值。如果你将&lt;pre&gt;{{ button | json }}&lt;/pre&gt; 放在循环中 - 你会看到什么?
  • 我不知道该怎么做 - 你的意思是 &lt;mat-button-toggle *ngFor="let button of buttonsFromApi" &lt;pre&gt;{{ button | json }}&lt;/pre&gt; [attr.id]="button.id" &gt;{{button.displayName}}&lt;/mat-button-toggle&gt; 吗? `
  • 作为另一个元素。例如,将其粘贴到 &lt;mat-button-toggle&gt; 旁边。甚至代替它。
  • 您必须在应用程序的某处附加-button
  • 我不是但mat-button-toggle可能...

标签: javascript angular ngfor


【解决方案1】:

如果您想覆盖(或更好地扩展)角度材质的默认按钮 ID,则必须传入 id。 (https://material.angular.io/components/button-toggle/api#MatButtonToggle)

<div>
  <mat-button-toggle id="test-123" value="right" aria-label="Text align right"></mat-button-toggle>
</div>

您将在组件中获取您的 id:

<mat-button-toggle ... id="test-123">
  <button class="mat-button-toggle-button" type="button" id="test-123-button" tabindex="0" aria-pressed="false" aria-label="Text align right">
<div class="mat-button-toggle-label-content"></div>
</button>
...
</mat-button-toggle>

【讨论】:

  • 是的,这就是我正在做的,但我希望组件具有100-button,只是100。我不知道你的回答如何解决这个问题。
  • @lte__ 适合您的组件是什么?
    + ?
【解决方案2】:

ID 应该用引号括起来

<div *ngFor="let button of buttonsFromApi" id="{{button.id}}">
  <mat-button-toggle>{{button.displayName}}</mat-button-toggle>
</div>

【讨论】:

  • 谢谢,但这并没有解决问题 - 它仍然生成为 100-button 等。
  • toggle &lt;mat-button-toggle&gt;{{button.id}}&lt;/mat-button-toggle&gt;987654323@中id的输出是什么
  • 确实可以,它输出为100 200 等。但是,如果我将它分配给id,它会添加-button
【解决方案3】:

使用方括号的属性绑定:

<div *ngFor="let button of buttonsFromApi" [attr.id]="button.id">

【讨论】:

  • 这会导致按钮获得像id="mat-button-toggle-0-button"这样的ID
猜你喜欢
  • 2018-10-01
  • 2019-02-05
  • 2020-01-25
  • 1970-01-01
  • 2019-09-16
  • 2019-07-24
  • 2021-10-24
  • 1970-01-01
  • 2018-04-15
相关资源
最近更新 更多