You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 8中如何为mat-list添加必填验证mat-error

嘿,我来帮你搞定这个表单需求!下面是具体的实现方案和代码示例,你可以直接参考:

核心实现思路
  • 列表项添加逻辑:通过输入框收集用户输入,点击添加按钮后将有效内容存入数组,同时清空输入框并刷新列表展示。
  • 列表渲染:根据存储的数组动态渲染列表项,还可以给每个项加上删除按钮,方便用户管理。
  • 提交验证:表单提交前先检查列表数组是否为空,为空就显示错误提示,否则执行正常提交流程。
完整代码示例(原生JS)
<form id="itemForm">
  <input type="text" id="itemInput" placeholder="输入要添加的列表项">
  <button type="button" id="addBtn">添加</button>
  <ul id="itemList" style="list-style: none; padding-left: 0;"></ul>
  <div id="errorMsg" style="color: #dc2626; margin: 8px 0; display: none;">⚠️ 列表不能为空,请至少添加一项!</div>
  <button type="submit">提交表单</button>
</form>

<script>
  // 获取DOM元素
  const itemInput = document.getElementById('itemInput');
  const addBtn = document.getElementById('addBtn');
  const itemList = document.getElementById('itemList');
  const errorMsg = document.getElementById('errorMsg');
  const itemForm = document.getElementById('itemForm');
  
  // 存储列表项的数组
  let items = [];

  // 添加列表项的点击事件
  addBtn.addEventListener('click', () => {
    const inputValue = itemInput.value.trim();
    if (inputValue) {
      items.push(inputValue);
      renderItemList();
      itemInput.value = '';
      errorMsg.style.display = 'none'; // 添加后隐藏错误提示
    }
  });

  // 渲染列表项的函数
  function renderItemList() {
    itemList.innerHTML = '';
    items.forEach((item, index) => {
      const listItem = document.createElement('li');
      listItem.style.display = 'flex';
      listItem.style.justifyContent = 'space-between';
      listItem.style.padding = '4px 8px';
      listItem.style.border = '1px solid #e5e7eb';
      listItem.style.marginBottom = '4px';
      
      listItem.textContent = item;
      
      // 添加删除按钮
      const deleteBtn = document.createElement('button');
      deleteBtn.textContent = '删除';
      deleteBtn.style.backgroundColor = '#ef4444';
      deleteBtn.style.color = 'white';
      deleteBtn.style.border = 'none';
      deleteBtn.style.borderRadius = '4px';
      deleteBtn.style.padding = '2px 6px';
      
      deleteBtn.addEventListener('click', () => {
        items.splice(index, 1);
        renderItemList();
      });
      
      listItem.appendChild(deleteBtn);
      itemList.appendChild(listItem);
    });
  }

  // 表单提交事件
  itemForm.addEventListener('submit', (e) => {
    e.preventDefault(); // 阻止默认表单提交行为
    if (items.length === 0) {
      errorMsg.style.display = 'block'; // 显示错误提示
    } else {
      errorMsg.style.display = 'none';
      // 这里写你的表单提交逻辑,比如发送API请求
      console.log('提交的列表内容:', items);
      alert('表单提交成功!');
    }
  });
</script>
关键细节说明
  • 输入内容会先做trim()处理,避免添加空字符串或纯空格的项。
  • 每次添加或删除项后,都会重新渲染列表,保证展示和数据一致。
  • 错误提示默认隐藏,只有提交时列表为空才显示,添加项后会自动隐藏。
  • 给列表项和按钮加了简单的样式,让界面更友好,你可以根据需求调整。

内容的提问来源于stack exchange,提问作者Mahesh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 18:52:38