【问题标题】:How do I make ngFor with input inside not repeat the typing value?如何使带有输入的 ngFor 不重复输入值?
【发布时间】:2022-01-16 02:25:47
【问题描述】:

我需要使用 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>

【问题讨论】:

    标签: javascript angular typescript ngfor


    【解决方案1】:

    您将所有输入绑定到单个属性comment.text。您应该为每个输入创建一个属性并将输入与它绑定。

    【讨论】:

    • 问题不在于数据输入(表单工作正常,每个“评论”都是在我想要的“出版物”中进行的)。问题在于撰写评论时,每次输入都会反映在所有输入中。
    • @AdrielSilvestre 如果这是真的,请更新您的问题以包含实际代码,因为这是您提交的问题的答案
    • @AluanHaddad 不好意思问题没看懂,我会努力写的更好
    • 问题是,我确实认为你所做的正是@NenadMilosavljevic 所说的那样。您尚未引入名为 comment 的循环范围变量,这意味着您绑定到迭代器之外范围内的成员
    【解决方案2】:

    您将变量“comment.text”绑定到每个输入 [模型]。意思是,它的值在所有输入范围之间共享。您需要使用“publication”,它仅适用于每个输入。

    *ngFor="let publication of publications"
    

    [(ngModel)]="comment.text" 更改为[(ngModel)]="publication.text" 之类的东西

    【讨论】:

    • “comment”是一个表,其中一个属性是“text”,我输入的值必须存储在那里。做出你说的改变没有意义。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-06
    • 2021-09-12
    • 2012-11-16
    • 1970-01-01
    • 2017-12-04
    • 1970-01-01
    • 2013-01-18
    相关资源
    最近更新 更多