网站搜索

javascript - 我如何使带有输入框的 ngFor 不重复输入的值?


我需要使用 ngFor 创建多个输入框,但当我输入一个单词时,它会在所有输入框中重复,我该如何解决这个问题?

我的代码:

    <div class="" *ngFor="let publication of publications">
            ...
        <form #newCommentForm="ngForm" (ngSubmit)="onSubmit(newCommentForm, $event, publication._id)">
           <div class="make-comment" >
              <img src="{{url+ 'get-image-user/' + publication.user.image }}" *ngIf="publication.user.image" class="rounded-circle-mini align-self-center">              
              <input type="text" name="#text" #text="ngModel" [(ngModel)]="comment.text" id="input-coment" class="form-control" required placeholder="Your comment">
              <button class="btn btn-sm btn-secondary" style="color: #fff;" type="submit"><i class="bi bi-arrow-bar-left"></i></button>    
            </div>
          </form>
        </div>

答案#1

你正在将变量 'comment.text' 绑定到每个输入 [model]。这意味着它的值在你所有的输入作用域之间是共享的。你需要使用 'publication',它只在每个输入的作用域内。

*ngFor="let publication of publications"

将 [(ngModel)]="comment.text" 改为类似 [(ngModel)]="publication.text" 的内容

答案#2

你正在将所有输入绑定到一个属性 comment.text。你应该为每个输入创建一个属性,并将输入绑定到该属性。