首页 \ 问答 \ 将输入字段绑定到ngFor循环内的按钮|(Bind input fields to buttons within ngFor loops | Angular 2+)

将输入字段绑定到ngFor循环内的按钮|(Bind input fields to buttons within ngFor loops | Angular 2+)

我正在尝试在窗体中创建一些数字输入,其旁边有+和 - 按钮,可以增加/减少数字值。 我使用存储在几个数组中的值创建输入和带有* ngFor循环的按钮。

但是我找不到一种方法将输入绑定到同一个* ngFor循环中创建的按钮。 我一直Cannot assign to a reference or variable!这个错误 - Cannot assign to a reference or variable!

我已经尝试过使用ngModel,只是绑定[value] 。 无论哪种方式我都会得到同样的错误

有没有另一种方法来做到这一点?

Stackblitz演示 - https://stackblitz.com/edit/angular-m3gkrq

我试过的代码 -

  <div class="border rounded p-4 m-1" *ngFor="let type of types">
    <div *ngFor="let subType of subTypes[type]">
      <label for="{{subType}}SlotsInput">{{type | titlecase}} : {{subType}}</label>
      <div class="input-group mb-3">
        <div class="input-group-prepend">
          <button class="btn btn-outline-secondary" type="button">-</button>
          <button class="btn btn-outline-secondary" type="button" (click)="(type+subType)++">+</button>
        </div>
        <input type="number" class="form-control" placeholder="0" id="{{subType}}SlotsInput"  min="0" max="10" [name]="type+subType" [(ngModel)]="type+subType">
      </div>
    </div>
  </div>

-

export class AppComponent  {
  types = ["dog", "horse", "hen", "elephant"];
  subTypes = {
    dog:["labrador", "vizsla"],
    horse:["arabian","shire","belgian"],
    hen:["plymouth rock", "leghorn", "bramha"],
    elephant:["african", "asian"]
  };

编辑:因为它不清楚,我希望+和 - 按钮增加/减少旁边输入字段中的数字。


I am trying to create some number inputs in a form with + and - buttons next to them which can increase/decrease the number values. I am creating the inputs and the buttons with *ngFor loops using values stored in a couple of arrays.

However I can't figure out a way to bind the inputs to buttons that are also created in the same *ngFor loops. I keep running into this error -- Cannot assign to a reference or variable!

I have tried using ngModel and just binding with [value]. I get the same error either way.

Is there another way to do this?

Stackblitz demo -- https://stackblitz.com/edit/angular-m3gkrq

Code that I have tried --

  <div class="border rounded p-4 m-1" *ngFor="let type of types">
    <div *ngFor="let subType of subTypes[type]">
      <label for="{{subType}}SlotsInput">{{type | titlecase}} : {{subType}}</label>
      <div class="input-group mb-3">
        <div class="input-group-prepend">
          <button class="btn btn-outline-secondary" type="button">-</button>
          <button class="btn btn-outline-secondary" type="button" (click)="(type+subType)++">+</button>
        </div>
        <input type="number" class="form-control" placeholder="0" id="{{subType}}SlotsInput"  min="0" max="10" [name]="type+subType" [(ngModel)]="type+subType">
      </div>
    </div>
  </div>

--

export class AppComponent  {
  types = ["dog", "horse", "hen", "elephant"];
  subTypes = {
    dog:["labrador", "vizsla"],
    horse:["arabian","shire","belgian"],
    hen:["plymouth rock", "leghorn", "bramha"],
    elephant:["african", "asian"]
  };

Edit: Incase it isn't clear, I want the + and - buttons to increase/decrease the number in the input field next to them.


原文:https://stackoverflow.com/questions/48954732
更新时间:2022-02-14 19:02

最满意答案

我强烈怀疑clas是一个null引用。 请注意,这仍将触发您的!= ""分支,因为空引用与空字符串不同。

也许用:

if(!string.IsNullOrEmpty(clas)) {...}

代替?

db-parameters的一个特性是,如果.Value为null则不包括它们。 检查您要发送的值。

它不适用于您的情况(因为在正常SQL中没有任何东西等于NULL)但是:如果您打算将NULL作为参数发送,则必须将值设置为DBNull.Value。


I have a strong suspicion that clas is a null reference. Note that this will still trigger your != "" branch, since a null-reference is not the same as an empty string.

Maybe use:

if(!string.IsNullOrEmpty(clas)) {...}

Instead?

A peculiarity of db-parameters is that they are not included if the .Value is null. Check the value you are sending in.

It doesn't apply in your case (since in normal SQL nothing ever equals NULL) but: if you intend to send NULL as a parameter, you must set the value to DBNull.Value instead.

相关问答

更多
  • 我上面的评论表明以下解决方案对您的问题。 CREATE FUNCTION getLotInfo(@suppliedLotId INTEGER) RETURNS TABLE AS RETURN ( SELECT combinedLotId, combinedCheckIn, combinedCheckOut, combinedStatusDesc, originTable FROM ( ...
  • 好吧显然我有一个完整的大脑放屁,看着错误的线路。 我改为这个并且它有效: db.Execute(@"INSERT INTO cdr_Requests (ReportId, ReportName, StartTime, EndTime, Status, ReportUrl, CreatedAt, UpdatedAt, Timezone, CdrReportRead) VALUES (@ReportId, @ReportName, @StartTime, @EndTime, @Status, @Rep ...
  • 你不应该执行一个字符串,而是执行一个DbCommand。 因此,首先使用打开的DbConnection创建一个DbCommand,将Commandtext设置为您的字符串,添加所有参数(例如@BillNo),然后执行命令。 You shoud not execute a string but execute a DbCommand. So first create a DbCommand using your open DbConnection, set the Commandtext to your st ...
  • 尝试改变这种说法 - SELECT @query = ' SELECT * FROM( SELECT PatientId, RTRIM(AttributeGroup) + ''_'' + RTRIM(AttributeId) AS ColName, FormId, Description FROM dbo.DVItems WHERE PatientId = ''' + CAST(@PatientId AS VARCH ...
  • 我强烈怀疑clas是一个null引用。 请注意,这仍将触发您的!= ""分支,因为空引用与空字符串不同。 也许用: if(!string.IsNullOrEmpty(clas)) {...} 代替? db-parameters的一个特性是,如果.Value为null则不包括它们。 检查您要发送的值。 它不适用于您的情况(因为在正常SQL中没有任何东西等于NULL)但是:如果您打算将NULL作为参数发送,则必须将值设置为DBNull.Value。 I have a strong suspicion that ...
  • 将@@ config声明放入@@ sql字符串中: Declare @SourceDatabase as nvarchar(10) Declare @DestDatabase as nvarchar(10) Declare @@sql as nvarchar(max) --variable to hold sql statements for this stored proc Declare @@Harray as nvarchar(max) -- variable to hold ...
  • 在连接条件中引用表时,必须使用别名 SELECT UOM FROM Item INNER JOIN @Temporary t ON Item.ItemID=t.AccountID 虽然这可以解决您遇到的问题,但您不需要临时表或游标。 此查询可以重写为: SELECT UOM FROM Item WHERE ItemID IN (SELECT DISTINCT ParentItem FROM ItemBillOfMaterial) You have to use an alias when refere ...
  • 你忘了启动DECLARE子句,在最后一行你省略了前两个变量之间的逗号: DECLARE @username varchar(50), @routenaam varchar(50), @van varchar(50), @naar varchar(50), @bezoekadres varchar(50), @geredenroute varchar(50), @karakterrit varchar(50), @toelichting v ...
  • 在指定命名参数时,对.Query的调用需要一个SqlParameter对象: var sqlUserName = new SqlParameter("@SellerLocationID", SellerLocationID); var results = unitofwork.DBContext().Database .SqlQuery ("Exec GetCl ...
  • 您正在添加名称参数: cmd.Parameters.AddWithValue("@usridmtld", usrid); cmd.Parameters.AddWithValue("@passwordmtld", usrpswd); 在您的查询中,参数存在冲突,请更改您的查询: Select usridmtld, passwordmtld from mobteldet.mobtellogin where usridmtld=@usridmtld and passwordmtld=@passwordmt ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)