【问题标题】:How do I give ngFor variable inside ngIf?如何在 ngIf 中提供 ngFor 变量?
【发布时间】:2019-05-06 13:45:36
【问题描述】:

我有这样的代码:

<span *ngFor="let track_type of model.content_id.track_types">
    <label class="col-3">{{track_type}} Stream ID*:</label>
    <input type="text" name="stream_id_{{track_type}}" class="col-offset-1 col-3" #stream_id="ngModel" placeholder="{{track_type}} Stream ID" required [(ngModel)]="model.stream_id">
    <span *ngIf="stream_id.invalid && (stream_id.dirty || stream_id.touched)" class="col-offset-2 col-5 text-danger">Stream ID is required</span>
    <br>
</span>

有两个问题:

  • 如果我编辑一个文本框,它会影响所有文本框。
  • 无法正确设置表单验证

如何解决这些问题?我尝试查看 ngTemplateOutlet,但它并没有按预期工作。

【问题讨论】:

  • 哈里莎。如果你有一个循环,你需要几个变量。不止一个。通常,如果我们迭代对象数组,它会使用数组或对象的属性。我对你的模型一无所知,但我想你想说[(ngModel)]="track_type"

标签: angular ngfor


【解决方案1】:

使用 trackByFunction

  trackByFn(index, item) {
    return index; // or item.id
  }

在你的模板中:

<span *ngFor="let track_type of model.content_id.track_types; trackBy: trackByFn">

【讨论】:

  • 这不是问题
  • "如果我编辑一个文本框,它会影响所有文本框。"解决这个问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-10-15
  • 2018-06-20
  • 1970-01-01
  • 2017-12-10
  • 2019-05-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多