如何以编程方式重置或取消选中 Angular 中的单选按钮?
Posted
技术标签:
【中文标题】如何以编程方式重置或取消选中 Angular 中的单选按钮?【英文标题】:How do I reset or Uncheck the Radio button in Angular programmatically? 【发布时间】:2021-06-30 15:10:54 【问题描述】:这是我使用单选按钮选择产品条件的 HTML 页面。当用户检查 New 或 used 按钮时,我会获取 New product 或 Used 产品:
<div>
<h5><b>Condition</b></h5>
<label class="container">New
<input (click)="onCondition('New')" type="radio" name="radio" >
<span class="checkmark"></span>
</label>
<label class="container">Used
<input (click)="onCondition('Used')" type="radio" name="radio" >
<span class="checkmark"></span>
</label>
</div>
这是我的单选按钮 CSS:
/* The container */
.container
display: block;
position: relative;
padding-left: 35px;
margin-bottom: 12px;
cursor: pointer;
font-size: 15px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
/* Hide the browser's default checkbox */
.container input
position: absolute;
opacity: 0;
cursor: pointer;
height: 0;
width: 0;
/* Create a custom checkbox */
.checkmark
position: absolute;
top: 0;
left: 0;
height: 25px;
width: 25px;
background-color: #eee;
/* On mouse-over, add a grey background color */
.container:hover input ~ .checkmark
background-color: #ccc;
/* When the checkbox is checked, add a blue background */
.container input:checked ~ .checkmark
background-color: #2196F3;
/* Create the checkmark/indicator (hidden when not checked) */
.checkmark:after
content: "";
position: absolute;
display: none;
/* Show the checkmark when checked */
.container input:checked ~ .checkmark:after
display: block;
/* Style the checkmark/indicator */
.container .checkmark:after
left: 9px;
top: 5px;
width: 5px;
height: 10px;
border: solid white;
border-width: 0 3px 3px 0;
-webkit-transform: rotate(45deg);
-ms-transform: rotate(45deg);
transform: rotate(45deg);
.slidecontainer
width: 100%;
.slider
-webkit-appearance: none;
width: 100%;
height: 25px;
background: #d3d3d3;
outline: none;
opacity: 0.7;
-webkit-transition: .2s;
transition: opacity .2s;
.slider:hover
opacity: 1;
.slider::-webkit-slider-thumb
-webkit-appearance: none;
appearance: none;
width: 25px;
height: 25px;
background: #4CAF50;
cursor: pointer;
.slider::-moz-range-thumb
width: 25px;
height: 25px;
background: #4CAF50;
cursor: pointer;
这是 TypeScript 函数,我想在执行此函数时重置或取消选中所有单选按钮。我希望能够将单选按钮取消选中为默认值:
/**
* Get current categories
* @param categoryId
*/
getCurrentCategories(categoryId: number)
this.currentCategories = categoryId;
【问题讨论】:
您可以在输入字段中动态添加/删除checked
属性。
【参考方案1】:
尝试给出一个 id='radio' 属性,然后给出 document.getElementById('radio').checked = false
【讨论】:
你从哪里得到'.checked'? 来自 W3 学校:w3schools.com/jsref/dom_obj_radio.asp。它对我有用 由于某种原因 .checked 不适合我。它不存在! const newElement = document.getElementById("new") as htmlInputElement; newElement.checked = false; const usedElement = document.getElementById("used") as HTMLInputElement; usedElement.checked = false;我用这种方式,它的工作原理谢谢!以上是关于如何以编程方式重置或取消选中 Angular 中的单选按钮?的主要内容,如果未能解决你的问题,请参考以下文章
Magento - 如何以编程方式取消选中超级产品属性上的“使用默认值”?