【发布时间】:2019-12-28 01:23:26
【问题描述】:
我正在尝试在 Angular 中创建一个简单的组件,该组件基本上将枚举映射到单选按钮输入。我已经设置并工作了,但是当我将该组件的多个实例放在一个页面上时,我遇到了一些奇怪的问题。我看到的是组件的两个副本相互反应。
这是针对使用 Angular 8 的项目。我已将代码分解为托管在此处的一个小项目,以便您查看发生了什么。托管组件是 app.component.html/.ts,单选按钮组件是 radio.component.html/.ts。
https://stackblitz.com/edit/angular-rcurne
编辑以在此处添加一些实际代码
app.component.html
<app-radio
[radioSelection]="selectionRadio1"
(radioSelectionChange)="selectionRadio1 = $event"
></app-radio>
<label>Radio Option Selected: {{ selectionRadio1.toString() }}</label>
<br />
<br />
<app-radio
[radioSelection]="selectionRadio2"
(radioSelectionChange)="selectionRadio2 = $event"
></app-radio>
<label>Radio Option Selected: {{ selectionRadio1.toString() }}</label>
radio.component.html
<div class="form-check">
<input
class="form-check-input"
type="radio"
name="radioInput"
id="radioInput1"
[value]="radioSelectionType.Option1"
[(ngModel)]="radioSelection"
(ngModelChange)="radioSelectionChangedByUser($event)"
/>
<label class="form-check-label" for="radioInput1">Option 1</label>
</div>
<div class="form-check">
<input
class="form-check-input"
type="radio"
name="radioInput"
id="radioInput2"
[value]="radioSelectionType.Option2"
[(ngModel)]="radioSelection"
(ngModelChange)="radioSelectionChangedByUser($event)"
/>
<label class="form-check-label" for="radioInput2">Option 2</label>
</div>
<div class="form-check">
<input
class="form-check-input"
type="radio"
name="radioInput"
id="radioInput3"
[value]="radioSelectionType.Both"
[(ngModel)]="radioSelection"
(ngModelChange)="radioSelectionChangedByUser($event)"
/>
<label class="form-check-label" for="radioInput3">Both</label>
</div>
radio.component.ts
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { RadioSelectionType } from './RadioSelectionType'
@Component({
selector: 'app-radio',
templateUrl: './radio.component.html'
})
export class RadioComponent implements OnInit {
@Input() radioSelection: RadioSelectionType;
@Output() radioSelectionChange = new EventEmitter<RadioSelectionType>();
public radioSelectionType = RadioSelectionType;
constructor() { }
ngOnInit() {
// If no default was specified via the input, default to Option 3
if (!this.radioSelection) {
this.radioSelection = RadioSelectionType.Option3;
}
}
radioSelectionChangedByUser(value: RadioSelectionType) {
this.radioSelectionChange.emit(this.radioSelection);
}
}
如上所述,我看到无线电输入会相互反应,即使它们是独立的组件。也请随意批评我的编码选择 - 我是一名 C# 开发人员,最近开始使用 Angular,所以我可能会遗漏一些关于它如何在网络上工作的内容。
【问题讨论】:
标签: javascript html angular typescript components