两个组件应用组件App
和IndividualComponent
之间存在父子关系。当我在子组件中更改一个teamMember
的类型时,其他位置的单选按钮也会更新。
请告诉我我在哪里理解错误以及如何纠正我的代码。
以下是涉及两个组件的整个代码:
//our root app component
import {Component, NgModule, VERSION, Input} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import { FormsModule } from '@angular/forms';
@Component({
selector: 'my-app',
template: `
<ul class="list-group list-group-flush">
<li [ngClass]="{'list-group-item':true}" *ngFor="let teamMember of teamMembers">
<div [ngClass]="{'bg-green':teamMember.type==='Good','bg-red':teamMember.type==='Bad'}">
<app-individual [teamMember]="teamMember"></app-individual>
</div>
</li>
</ul>
`,
})
export class App {
teamMembers: Array<{ name: string, type: 'Good' | 'Bad' }>;
constructor() {
this.teamMembers = new Array();
this.teamMembers.push({ name: 'Member 1', type: 'Good' });
this.teamMembers.push({ name: 'Member 2', type: 'Good' });
this.teamMembers.push({ name: 'Member 3', type: 'Good' });
this.teamMembers.push({ name: 'Member 4', type: 'Good' });
this.teamMembers.push({ name: 'Member 5', type: 'Good' });
this.teamMembers.push({ name: 'Member 6', type: 'Good' });
}
}
@Component({
selector: 'app-individual',
template:`
<h3>{{teamMember.name}} -- {{teamMember.type}}</h3>
<div class="form-group">
<label>
<input type="radio" [(ngModel)]="teamMember.type" [value]="'Good'"> Good
</label>
<label>
<input type="radio" [(ngModel)]="teamMember.type" [value]="'Bad'"> Bad
</label>
</div>
`;
})
export class IndividualComponent {
constructor() { }
@Input() teamMember;
}
@NgModule({
imports: [ BrowserModule,FormsModule ],
declarations: [ App, IndividualComponent ],
bootstrap: [ App ]
})
export class AppModule {}
答案 0 :(得分:3)
您只是忘记设置输入的名称。
只需添加[name]="teamMember.name"
,然后添加will work fine。
答案 1 :(得分:2)
单选按钮需要具有唯一的name
属性。
如果您向name="{{teamMember.name}}
添加[name]="teamMember.name
(或<input type="radio" ...>
,它应该再次有用。